简体   繁体   English

如何在Python中从dict获取嵌套值

[英]How to get the nested values from dict in Python

I have this dict 我有这个命令

{
    'name': 'Katty', 
    'assignment': [80, 50, 40, 20],
    'test': [75, 75], 
    'lab': [78.2, 77.2]
}

I am expecting to get this output: 我期望得到以下输出:

80
50
40
20
75
75
78.2
77.2

But I am getting only the numbers for assignment and I don't want to do 3 different loops (for assignment, test, and lab). 但是我只得到分配的数字,我不想做3个不同的循环(分配,测试和实验)。 Is there any better solution to get my desired output? 有没有更好的解决方案来获得所需的输出?

This is what I have so far: 这是我到目前为止的内容:

for i in Katty['assignment']:
    print(i)

80
50
40
20
d = {'name': 'Katty', 'assignment': [80, 50, 40, 20], 'test': [75, 75], 'lab': [78.2, 77.2]}

output = []

for val in d.values():
    if isinstance(val, list):
        output += val

print(output) # [80, 50, 40, 20, 75, 75, 78.2, 77.2]

or one-liner: 或单线:

output = [x for val in d.values() if isinstance(val, list) for x in val]

For your desired output you can unpack it to print it without commas or brackets: 对于所需的输出,您可以将其打开包装以使其打印而无需逗号或括号:

print(*output)

Note that order of the output can not be guaranteed unless you use an OrderedDict or use Python3.7+ where dict s are in insertion order. 请注意,除非您使用OrderedDict或在插入顺序为dict的情况下使用Python3.7 +,否则无法保证输出的顺序。

Katty = {'name': 'Katty', 'assignment': [80, 50, 40, 20], 'test': [75, 75], 'lab': [78.2, 77.2]} print(Katty['assignment'] + Katty['test'] + Katty['lab'])

If, 如果,

data = {'name': 'Katty', 'assignment': [80, 50, 40, 20], 'test': [75, 75], 'lab': [78.2, 77.2]}

here is the flattened list of values in your map, by taking every value that are of type list and then taking every value out of that list, 这是地图中的扁平化值列表,方法是获取list类型的每个值,然后从该列表中获取每个值,

list_values = [value for values in data.values() if type(values) == list for value in values]

And to convert this list into a string of value converted by spaces : 并将此列表转换为由空格转换的值字符串:

list_values_str = " ".join(map(str, list_values))

Refer to the documentation to understand what join and map do. 请参考文档以了解联接和映射的作用。

Here's a one line to print values for "assignments", "test", "lab" 这是一行,用于打印“任务”,“测试”,“实验室”的值

print(*(d['assignments'] + d['test'] + d['lab']))

The addition operation on lists using + appends the lists. 使用+对列表进行的加法运算会追加列表。

So the result of d['assignments'] + d['test'] + d['lab'] will be a new list having the elements from all these lists. 因此, d['assignments'] + d['test'] + d['lab']将是一个包含所有这些列表中的元素的新列表。

Placing the * before the list in printing unpacks the elements and separates between them using spaces. *放在打印列表的前面,将元素拆包,并使用空格分隔它们。

If you want commas instead or other separator you can specify that in the print statement like this 如果要使用逗号或其他分隔符,则可以在打印语句中指定该格式,如下所示

print(*(d['assignments'] + d['test'] + d['lab']), sep=',')

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

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