Dove
Dove

Reputation: 13

Complex nested dictionary from a dataframe

I have a list called rest which contains many dictionaries in a list which is in the format

rest = [{'a':'b','c':'d','e':'f'}, {'a':'g','c':'h','e':'i}, {'a':'j','c':'k','e':'l'}]

Can I get an output as below where I have new as a key inside a dictionary for all the key-value pair except the first key-value pair

output = [{'a':'b','new':{'c':'d','e':'f'}},{'a':'g','new':{'c':'h','e':'i'}},{'a':'j','new':{'c':'k','e':'l'}}]

Is it possible?

Upvotes: 1

Views: 46

Answers (1)

a_guest
a_guest

Reputation: 36249

You can use the syntax first, *remainder to extract the relevant parts and then create a new dict from them:

def convert(d):
    first, *remainder = d.items()
    return dict([first, ('new', dict(remainder))])

Then to convert each of the dicts:

output = [convert(d) for d in rest]

Note that this syntax was introduced in Python 3.0 and dictionaries are unordered before Python 3.6 (i.e. the first item is not determined).

Upvotes: 1

Related Questions