Dave Wilson
Dave Wilson

Reputation: 37

Converting Dictionary Values to new Dictionary

I am pulling json data from an API and have a number of columns in my dataframe that contain dictionaries. These dictionaries are written so that the id and the value are two separate entries in the dictionary like so:

{'id': 'AnnualUsage', 'value': '13071'}

Some of the rows for these columns contain only one dictionary entry like shown above, but others can contain up to 7:

[{'id': 'AnnualUsage', 'value': '13071'},
 {'id': 'TestId', 'value': 'Z13753'},
 {'id': 'NumberOfMe', 'value': '3'},
 {'id': 'Prem', 'value': '960002'},
 {'id': 'ProjectID', 'value': '0039'},
 {'id': 'Region', 'value': 'CHR'},
 {'id': 'Tariff', 'value': 'Multiple'},
 {'id': 'Number', 'value': '06860702'}]

When I attempt to break this dictionary down into separate column attributes

CTG_df2 = pd.concat([CTG_df['id'], CTG_df['applicationUDFs'].apply(pd.Series)], axis=1)

I end up with columns in a dataframe each containing a dictionary of the above entry i.e.

{'id': 'AnnualUsageDE', 'value': '13071'}

Is there a way for me to convert my dictionary values into new key-value pairs? For instance I would like to convert from:

{'id': 'AnnualUsageDE', 'value': '13071'}

to

{'AnnualUsageDE': '13071'}

If this is possible I will then be able to create new columns from these attributes.

Upvotes: 2

Views: 1785

Answers (2)

Hippolippo
Hippolippo

Reputation: 813

You can iterate through the values and set each of them to the dictionary value:

newdict = dict()
for x in original:
    newdict[x["id"]] = x["value"]

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

You can do a dict comprehension. From your list of dicts, compose a new dict where the key is the id of each element and the value is the value of each element.

original = [{'id': 'AnnualUsage', 'value': '13071'},
            {'id': 'TestId', 'value': 'Z13753'},
            {'id': 'NumberOfMe', 'value': '3'},
            {'id': 'Prem', 'value': '960002'},
            {'id': 'ProjectID', 'value': '0039'},
            {'id': 'Region', 'value': 'CHR'},
            {'id': 'Tariff', 'value': 'Multiple'},
            {'id': 'Number', 'value': '06860702'}]

newdict = {subdict['id']: subdict['value'] for subdict in original}
print(newdict)
# {'AnnualUsage': '13071',
#  'Number': '06860702',
#  'NumberOfMe': '3',
#  'Prem': '960002',
#  'ProjectID': '0039',
#  'Region': 'CHR',
#  'Tariff': 'Multiple',
#  'TestId': 'Z13753'}

Upvotes: 4

Related Questions