Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Moving value in front of dictionary inside dictionary as key/value

can anyone help me with adding the numbers in front of the ":" (1, 11014, 11019) as a key/value inside the list of dictionaries? I can’t seem to figure out how to access it. Thank you!

df = {1: [{'Weekday': 'Sunday',
   'StartTime': 9.0,
   'EndTime': 9.0,
   'Duration': 0.0},
  {'Weekday': 'Monday',
   'StartTime': 9.0,
   'EndTime': 17.0,
   'Duration': 8.0}],
 11014: [{'Weekday': 'Sunday',
   'StartTime': 9.0,
   'EndTime': 9.0,
   'Duration': 0.0},
  {'Weekday': 'Monday',
   'StartTime': 9.0,
   'EndTime': 17.0,
   'Duration': 8.0}],
 11019: [{'Weekday': 'Sunday',
   'StartTime': 9.0,
   'EndTime': 9.0,
   'Duration': 0.0}]}

I would want something like:

df = [{'Id' : 1,
'Weekday': 'Sunday',
   'StartTime': 9.0,
   'EndTime': 9.0,
   'Duration': 0.0} 

...]

I tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for i in df:
    i['UserId'] = i 
print(df)

>Solution :

You can do it by iterating through your key and values like this:

output_list = []
for k, v_list in df.items():
    for v in v_list:
        v['id'] = k
        output_list.append(v)

EDIT: since your values are in list

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading