Python printing lists of dictionary values ​​on one line

I have a dictionary that has lists as values:

my_dict = {'key1': ['foo1','foo2'],
           'key2': ['bar1', 'bar2'],
           'key3': ['foobar1', 'foobar2'}

      

I would like to find a dictionary for several keys and store their values ​​in a list:

keys = []
values = []
for k,v in my_dict.items():
    if k.startswith(('key1', 'key3')):
        keys.append(k)
        values.append(v)

      

But when I do that, I get a list of multidimensional (double brackets) for values. If I replace values.append(v)

with print(v)

, I will get the values ​​on 2 separate lines. My question is, how can I print lists of values ​​from two separate keys on one line?

+3


source to share


2 answers


One of the many ways to print a nested list on one line with understanding:

print(*[i for sub in values for i in sub])

      



If you don't want it to be nested in the first place, replace append

with extend

in values.append(v)

.

list.extend

takes a list (in this case v

) and adds all of its elements to another list. list.append

it just adds the item as if it were a new list, which results in a nested structure.

+2


source


Your problem appears in spring due to the fact that you separately add multiple lists to the list values

. That is, you do:

values = []

values.append(['foo1','foo2'])  

# values = [ ['foo1','foo2'] ]

values.append(['foobar1', 'foobar2']) 

# values = [ ['foo1'...], ['foobar1'...] ]

      



To make the values ​​a single list of only strings, use values.extend(v)

. The method .extend()

concatenates the lists, and the method concatenates append

them.

values.extend(v)

# or:

values += v

      

+2


source







All Articles