Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dictionaries
#1
Hello everybody,

I read data from an MySQL server and it gives me the info as a list dictionaries:

db_ewon =  con.cursor(dictionary=True)
db_ewon.execute("SELECT Name,Id FROM esync_stations")
df_ewon = db_ewon.fetchall()

for x in df_ewon[0:5]:
    print (x)
The result:

{'Name': 'Station1', 'Id':1}
{'Name': 'Station2', 'Id':5}
{'Name': 'Station3', 'Id':3}
{'Name': 'Station4', 'Id':9}
{'Name': 'Station5', 'Id':2}
I want to put all this data in 1 dictionary with the heads: 'Name' and 'Id'
The dictionary looks like this:

new_dict={
    'Station1':1,
    'Station2':5,
    'Station3':3,
    'Station4':9,
    'Station5':2,
}
Can somebody help me please
Reply
#2
dict comprehension:
new_dict = {item['Name']:item['Id'] for item in df_ewon[0:5]}
note you can also iterate over cursor as iterator - https://dev.mysql.com/doc/connector-pyth...chone.html
example from the docs
# Using the cursor as iterator
cursor.execute("SELECT * FROM employees")
for row in cursor:
  print(row)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
As you know the key names, you can use a simple dictionary comprehension with a for loop to step through the list.

For example,

list_ = [{'Name': 'Station1', 'Id':1},
{'Name': 'Station2', 'Id':5},
{'Name': 'Station3', 'Id':3},
{'Name': 'Station4', 'Id':9},
{'Name': 'Station5', 'Id':2}]

new_dict = {dict_['Name']: dict_['Id'] for dict_ in list_}
print(new_dict)
I am trying to help you, really, even if it doesn't always seem that way
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020