I would like to write for loop in one line:
d = {'a': [1, 2, 3], 'b': [5, 6, 7], 'c': [9, 0]}
my_list = []
for k, v in d.items():
for x in v:
my_list.append(x)
How can I do it?
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.
The one-liner dict(enumerate(a)) first creates an iterable of (index, element) tuples from the list a using the enumerate function. The dict() constructor than transforms this iterable of tuples to (key, value) mappings. The index tuple value becomes the new key . The element tuple value becomes the new value .
The methods dict. keys() and dict. values() return lists of the keys or values explicitly.
Lists are mutable data types in Python. Lists is a 0 based index datatype meaning the index of the first element starts at 0. Lists are used to store multiple items in a single variable. Lists are one of the 4 data types present in Python i.e. Lists, Dictionary, Tuple & Set.
>>> d = {'a': [1, 2, 3], 'b': [5, 6, 7], 'c': [9, 0]}
>>> [y for x in d.values() for y in x]
[1, 2, 3, 9, 0, 5, 6, 7]
This is a nested list comprehension. To show how this works, you can break it up into lines to see it's structure as nested for
loops. It goes from left to right.
[y
for x in d.values()
for y in x]
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