Reputation: 211
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
Upvotes: 0
Views: 61
Reputation: 3142
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.
Upvotes: 2
Reputation: 7897
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.
Upvotes: 4
Reputation: 1272
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=',')
Upvotes: 1
Reputation: 528
Katty = {'name': 'Katty', 'assignment': [80, 50, 40, 20], 'test': [75, 75], 'lab': [78.2, 77.2]}
print(Katty['assignment'] + Katty['test'] + Katty['lab'])
Upvotes: 2