简体   繁体   中英

Python Dictionary Insert multilevel values

I would like to transform the following dictionary:

dict_ = {'/xxx/xxx': 
         {'Price': '460.000','Location': 'France'},
'/yyy/yyy': {'Price': '360.000','Location': 'Germany'},
'/fff/ff': {'Price': '149.000','Location': 'Russia'},
'/aaa/aaa': {'Price': '150.000','Location': 'UK'}}
print(dict_)

Would like to add a date level, as shown:

dict_ = {'/xxx/xxx':{'2022/01/28':{'Price': '460.000','Location': 'France'}},
        '/yyy/yyy': {'2022/01/28' :{'Price': '360.000','Location': 'Germany'}},
        '/fff/ff':  {'2022/01/28': {'Price': '149.000','Location': 'Russia'}},
        '/aaa/aaa': {'2022/01/28': {'Price': '150.000','Location': 'UK'}}}

AND the 2nd option to add date as following:

dict_ = {'2022/01/28' : {'/xxx/xxx': 
         {'Price': '460.000','Location': 'France'},
'/yyy/yyy': {'Price': '360.000','Location': 'Germany'},
'/fff/ff': {'Price': '149.000','Location': 'Russia'},
'/aaa/aaa': {'Price': '150.000','Location': 'UK'}}}

Thank you

dict_ = {
    '/xxx/xxx': {'Price': '460.000','Location': 'France'},
    '/yyy/yyy': {'Price': '360.000','Location': 'Germany'},
    '/fff/ff': {'Price': '149.000','Location': 'Russia'},
    '/aaa/aaa': {'Price': '150.000','Location': 'UK'}
}
print(dict_)

date='2022/01/28'
d2={}
d3={date:{}}
for key, value in dict_.items():
    d2[key] = {date:value}
    d3[date][key]=value

print('first option')
print(d2)
print('second option')
print(d3)

Result for d2

{'/xxx/xxx': {'2022/01/28': {'Price': '460.000', 'Location': 'France'}},
 '/yyy/yyy': {'2022/01/28': {'Price': '360.000', 'Location': 'Germany'}},
 '/fff/ff': {'2022/01/28': {'Price': '149.000', 'Location': 'Russia'}},
 '/aaa/aaa': {'2022/01/28': {'Price': '150.000', 'Location': 'UK'}}}

Result for d3

{'2022/01/28': {'/xxx/xxx': {'Price': '460.000', 'Location': 'France'},
  '/yyy/yyy': {'Price': '360.000', 'Location': 'Germany'},
  '/fff/ff': {'Price': '149.000', 'Location': 'Russia'},
  '/aaa/aaa': {'Price': '150.000', 'Location': 'UK'}}}

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