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?
source to share
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.
source to share
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
source to share