I have a list of dictionaries like in this example:
listofdict = [{'name': 'Foo', 'two': 'Baz', 'one': 'Bar'}, {'name': 'FooFoo', 'two': 'BazBaz', 'one': 'BarBar'}]
I know that 'name' exists in each dictionary (as well as the other keys) and that it is unique and does not occur in any of the other dictionaries in the list.
I would like a nice way to access the values of 'two' and 'one' by using the key 'name'. I guess a dictionary of dictionaries would be most convenient? Like:
{'Foo': {'two': 'Baz', 'one': 'Bar'}, 'FooFoo': {'two': 'BazBaz', 'one': 'BarBar'}}
Having this structure I can easily iterate over the names as well as get the other data by using the name as a key. Do you have any other suggestions for a data structure?
My main question is: What is the nicest and most Pythonic way to make this transformation?
To merge multiple dictionaries, the most Pythonic way is to use dictionary comprehension {k:v for x in l for k,v in x. items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.
Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.
d = {}
for i in listofdict:
d[i.pop('name')] = i
if you have Python2.7+:
{i.pop('name'): i for i in listofdict}
dict((d['name'], d) for d in listofdict)
is the easiest if you don't mind the name
key remaining in the dict
.
If you want to remove the name
s, you can still easily do it in one line:
dict(zip([d.pop('name') for d in listofdict], listofdict))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With