Home > Software engineering >  Take a specific value from a list of dictionaries and use the value as a new key in a list of nested
Take a specific value from a list of dictionaries and use the value as a new key in a list of nested

Time:10-21

I am still relatively new to python and trying to teach myself different things. However, this issue has stumped me. I have a list of dictionaries. I want to extract the value of SourceKey from the dictionary and use that value as a new key within the list that also contains all the rest of the dictionary entries inside the new key (I hope that didn't sound too confusing). For example:

data = [
{'AssetId':'1234',
 'CreatedById':'02i3s',
 'Billable__c': True,
 'SourceKey': '00a1234'},
{'AssetId':'4567',
 'CreatedById':'03j8t',
 'Billable__c':True,
 'SourceKey': '00b4321'}
]

So now I want to take the value from SourceKey to create a dictionary of dictionaries so it looks like this:

new_data = [
  {'00a1234': {'AssetId':'1234',
               'CreatedById':'02i3s',
               'Billable__c': True},
  {'00b4321': {'AssetId':'4567',
               'CreatedById':'03j8t',
               'Billable__c':True}
]

I basically have this starting point, but I'm just stuck on how to put the key-value pairs of the nested dictionary inside the new value from SourceKey because I know I need to replace the ___ with the key-values from the rest of data:

[new_data] = {}
for row in data:
  if row['SourceKey']:
    new_data.update(row['SourceKey'], ___)

Any help would be fantastic!

CodePudding user response:

You're defining [new_data] as dict but you actually want new_data as dictionary.
Use comprehension to get the content of data without SourceKey:

from pprint import pprint
data = [
{'AssetId':'1234',
 'CreatedById':'02i3s',
 'Billable__c': True,
 'SourceKey': '00a1234'},
{'AssetId':'4567',
 'CreatedById':'03j8t',
 'Billable__c':True,
 'SourceKey': '00b4321'}
]

new_data = dict()
for row in data:
  if row['SourceKey']:
    new_data[row['SourceKey']] = {k:v for k,v in row.items() if k != 'SourceKey'}

pprint(new_data)

Output:

{'00a1234': {'AssetId': '1234', 'Billable__c': True, 'CreatedById': '02i3s'},
 '00b4321': {'AssetId': '4567', 'Billable__c': True, 'CreatedById': '03j8t'}}
  • Related