简体   繁体   中英

How to merge a dict into nested dict in python with particular format?

I have a dictionary as:

digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 }

I want the new nested dictionary to be made like this:

new_dict = [{'eng':'one','math': 1}
            {'eng':'two','math': 2}
            {'eng':'three','math': 3}
            {'eng':'four','math': 4}
            {'eng':'five','math': 5}
           ]

I tried this:

digit = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5 }
new_dict={'eng':'','math':''}

for nest_key,nest_val in new_dict.items():
    for (key,value),(k,v) in nest_val.items(), digit.items():
        if nest_val['eng'] == '':
            nest_val.update({k:v})  
        nest_val.append({k:v})

print(new_dict)

Gives this error:

  for (key,value),(k,v) in nest_val.items(), digit.items():  
AttributeError: 'str' object has no attribute 'items'

As I mentioned in comments, nest_val is actually the value which is a string and doesn't have an items() method. Besides that, you don't have to create another dictionary and update it by multiple loops like that. Instead, you can create your desire dictionaries by one loop over the items.

lst = []
for name, val in digit.items():
    lst.append({'eng': name,'math': val})

And in a more Pythonic way you can just use a list comprehension to refuse appending to the list at each iteration.

lst = [{'eng': name,'math': val} for name, val in digit.items()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM