Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python one line save values of lists in dict to list

Tags:

python

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?

like image 438
bandit Avatar asked Apr 12 '13 08:04

bandit


People also ask

How do you turn the values of a dictionary into a list?

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.

How do you make a dictionary one line?

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 .

Does dict values () return a list?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly.

Can Python dictionary store lists?

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.


1 Answers

>>> 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]
like image 148
jamylak Avatar answered Nov 14 '22 21:11

jamylak