python - create nested dictionarys in python3 -


i create nested dict in python3, i've following list(from sql-query):

 [('madonna', 'portland', 'oregon', '0.70', '+5551234', 'music', datetime.date(2016, 9, 8), datetime.date(2016, 9, 1)), ('jackson', 'laredo', 'texas', '2.03', '+555345', 'none', datetime.date(2016, 5, 23), datetime.date(2016, 5, 16)), ('bohlen', 'p', 'p', '2.27', '+555987', 'phd student', datetime.date(2016, 9, 7))] 

i have following output:

{madonna:{city:portland, state:oregon, index: 0.70, phone:+5551234, art:music, exp-date:2016, 9, 8, arrival-date:datetime.date(2016, 5, 23)},jackson:{city: laredo, state:texas........etc...}} 

can show me easy understand code?

i try:

from collections import defaultdict usercheck = defaultdict(list) accname,  div_ort,  standort,  raum,  telefon,  position,  exp, dep in cur.fetchall():     usercheck(accname).append[..] 

but don't work, can't think further myself

you can use dict comprehension (defined here) dynamically create dictionary based on elements of list:

sql_list = [     ('madonna', 'portland', 'oregon', '0.70', '+5551234', 'music', datetime.date(2016, 9, 8), datetime.date(2016, 9, 1)),     ('jackson', 'laredo', 'texas', '2.03', '+555345', 'none', datetime.date(2016, 5, 23), datetime.date(2016, 5, 16)),     ('bohlen', 'p', 'p', '2.27', '+555987', 'phd student', datetime.date(2016, 9, 7)) ] sql_dict = {     element[0]: {         'city': element[1],         'state': element[2],         'index': element[3],         'phone': element[4],         'art': element[5],     } element in sql_list } 

keep in mind every item in dictionary needs have key , value, , in example have few values no key.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -