snippetpythonModerate
Convert a list of dictionaries to a dictionary of dictionaries
Viewed 0 times
convertlistdictionariesdictionary
Problem
I need to convert a list of dictionaries to a dictionary of dictionaries, with a particular item as the new key.
This is the way I'm currently doing it:
However, this looks really ugly to me. Is there a more elegant way to do this?
This is the way I'm currently doing it:
>>> a
[{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}]
>>> {
item['id']:{
sub_item:item[sub_item] for sub_item in item if sub_item != 'id'
} for item in a}
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}However, this looks really ugly to me. Is there a more elegant way to do this?
Solution
While using methods with side effects in list- or dict-comprehensions is generally frowned upon, in this case you could make use of
Keep in mind, though, that this will alter the dictionary in-place, i.e. afterwards:
If you do not want to alter the original dictionaries, use
dict.pop to get the id and at the same time remove it from the dictionary.>>> a = [{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}]
>>> {d.pop("id"): d for d in a}
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}Keep in mind, though, that this will alter the dictionary in-place, i.e. afterwards:
>>> a
[{'bar': 'baz'}, {'bar': 'baz'}]If you do not want to alter the original dictionaries, use
map(dict, a) to create copies before poping elements from those, leaving the original dicts in a as they were.>>> {d.pop("id"): d for d in map(dict, a)}
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}Code Snippets
>>> a = [{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}]
>>> {d.pop("id"): d for d in a}
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}>>> a
[{'bar': 'baz'}, {'bar': 'baz'}]>>> {d.pop("id"): d for d in map(dict, a)}
{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}Context
StackExchange Code Review Q#85625, answer score: 14
Revisions (0)
No revisions yet.