简体   繁体   English

在同一行python上打印字典值列表

[英]Printing lists of dictionary values on the same line python

I have a dictionary that has lists as the values: 我有一个字典列表作为值:

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

I'd like to search the dictionary for multiple 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 this I get a multidimensional (double brackets) list for values. 但是当我这样做时,我得到一个值的多维(双括号)列表。 If I were to replace values.append(v) with print(v) I get the values on 2 separate lines. 如果我用print(v)替换values.append(v) ,我会在2个单独的行上获取值。 My question is, how can I print the value lists from 2 separate keys on the same line? 我的问题是,如何从同一行的2个单独的键打印值列表?

One of the many ways you can print a nested list in one line is with a comprehension: 您可以在一行中打印嵌套列表的众多方法之一是理解:

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

If you didn't want it to be nested in the first place, replace append with extend in values.append(v) . 如果您不希望它首先嵌套,请在values.append(v)使用extend替换append

list.extend takes a list (as v is in this case) and add all its elements to the other list. list.extend获取一个列表(在本例中为v )并将其所有元素添加到另一个列表中。 list.append just adds the element as is to the new list resulting in the nested structure you see. list.append只是将元素按list.append添加到新列表中,从而得到您看到的嵌套结构。

Your problem appears to spring from the fact that you are separately appending more than one list to the values list. 您的问题似乎源于您将多个列表单独附加到values列表的事实。 That is, you are doing: 也就是说,你正在做:

values = []

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

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

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

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

In order to get values to be a single list of just the strings, use values.extend(v) . 为了使值成为仅包含字符串的单个列表,请使用values.extend(v) The .extend() method concatenates lists, while the append method nests them. .extend()方法连接列表,而append方法则嵌套它们。

values.extend(v)

# or:

values += v

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM