I have a dictionary in python 2.7 that has the following structure:
x = {
'1': ['a', 'b', 'c'],
'2': ['d', 'e', 'f']
}
The length of the value list is always the same and I would like to basically zip the value lists with corresponding values. So, in this case it will create three new lists as:
[['a', 'd'], ['b', 'e'], ['c', 'f']]
I know I can write an awful looking loop to do this but I was wondering if there is a more pythonic way to do this. I need to preserve the order.
Answer. If the list passed to the zip() function contains duplicate data, the duplicate created as part of the list comprehension will be treated as an update to the dictionary and change the value associated with the key. No error will be reported.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python. But we can have a similar effect as keeping duplicate keys in dictionary.
zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.
To create a dictionary from two sequences, use the dict() and zip() method. The dict(zip(keys, values)) needs the one-time global lookup each for dict and zip.
You can do the following:
zip(*x.values())
Explanation:
x.values()
returns [['a', 'b', 'c'], ['d', 'e', 'f']]
(order may change so you might need to sort x
first.)
zip([a, b], [c, d])
returns [[a, c], [b, d]]
x.values()
into arguments to zip
, prepend *
to it.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