I have a dictionary of dictionaries:
d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}
And I want to convert it to:
new_d = {"x":[1, 2, 3], "y": [2, 3, 4], "z": [3, 4, 5]}
The requirement is that new_d[key][i]
and new_d[another_key][i]
should be in the same sub-dictionary of d
.
So I created new_d = {}
and then:
for key in d.values()[0].keys():
new_d[key] = [d.values()[i][key] for i in range(len(d.values()))]
This gives me what I expected, but I am just wondering if there are some built-in functions for this operation or there are better ways to do it.
In Python, a dictionary provides method items() which returns an iterable sequence of all elements from the dictionary. The items() method basically converts a dictionary to a list along with that we can also use the list() function to get a list of tuples/pairs.
To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.
In Python dictionary, it is an unordered and immutable data type and can be used as a keys element. To create a dictionary of lists, first, we insert key-value within the curly brackets and to obtain the values of a dictionary, and then use the key name within the square brackets.
You can have dicts inside of a list. The only catch is that dictionary keys have to be immutable, so you can't have dicts or lists as keys.
There is no built-in function for this operation, no. I'd just loop over values
directly:
new_d = {}
for sub in d.itervalues(): # Python 3: use d.values()
for key, value in sub.iteritems(): # Python 3: use d.items()
new_d.setdefault(key, []).append(value)
This avoids creating a new list for the dict.values()
call each time.
Note that dictionaries have no order. The values in the resulting lists are going to fit your criteria however; they'll be added in the same order for each of the keys in new_d
:
>>> d = {"a": {"x":1, "y":2, "z":3}, "b": {"x":2, "y":3, "z":4}, "c": {"x":3, "y":4, "z":5}}
>>> new_d = {}
>>> for sub in d.values():
... for key, value in sub.items():
... new_d.setdefault(key, []).append(value)
...
>>> new_d
{'x': [1, 2, 3], 'y': [2, 3, 4], 'z': [3, 4, 5]}
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