简体   繁体   中英

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). 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.

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_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.

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=',')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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