简体   繁体   中英

How to print one specific value from each key in a dictionary in Python?

I have a dictionary consisting of 4 keys with 3 values per key.

Looks like this: d = {key1: (value1, value2, value), key2: (value1, value2, value), key3: (value1, value 2, value3)}

I want to print value1 from all of the keys. The way I have done it now is like this:

print (persons['1'][0])
print(persons['2'][0])
print (persons['3'][0])
print(persons['4'][0])

But I guess there is an easier way so that I can refer to all the keys in just one line? I also want to find the highest value2 in all the keys, and the average from value3 in all keys. Can someone please help me with this?

You can use for loop to iterate:

d = {'test1': (1, 2, 3), 'test2': (4, 5, 6), 'test3': (7, 8, 9)}
for key in d.values():
    print(key[0])

what about?

d = {
    "key1": (1,2,3),
    "key2": (3,4,5),
    "key4": (5,6,8),
}

[ print(val[0]) for _, val in d.items()]

Try this bro:

d = {"key1": (5, 2, 6), "key2": (6, 7, 3), "key3": (5, 7, 9)}
for i in d:
    print(d[i][0])

you can achive this using list comprehension:

persons = {'1': (1,2,3), '2': (4,5,6), '3': (7,8,9)}

# First Value's
first_values = " ".join([str(x[0]) for x in persons.values()])
print(first_values)   # prints 1 4 7

# Max of second value's
max_value2 = max([x[1] for x in persons.values()])
print(max_value2)  # prints 8

# Average of value3's
third_values = [x[2] for x in persons.values()]
average_of_third_values = sum(third_values) / len(third_values)

# in case avoid zero division  : 
# average_of_third_values = sum(third_values) / (len(third_values) or 1)

print(average_of_third_values)  # prints 6

# to get value1 of values which has max value2
value1_of_max = [x[0] for x in persons.values() if x[1]==max_value2]
print(value1_of_max)  # prints [7]
# Its possible to be exist more than 1 person that has value2 which equals to max number, like so
# persons = {'1': (1,2,3), '2': (4,8,6), '3': (7,8,9)}
# so we print them as list

You can convert your dict into a DataFrame which will make things very easy for you:

from pandas.DataFrame import from_dict
d = {'a':(1,2,3),'b':(4,5,6)}
d = from_dict(d, orient='index')
d[0] # print values of value1
d[1].max() # max of value2
d[2].mean() # mean of value3

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