简体   繁体   English

如何从 Python 字典中的每个键打印一个特定值?

[英]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.我有一个由 4 个键组成的字典,每个键有 3 个值。

Looks like this: d = {key1: (value1, value2, value), key2: (value1, value2, value), key3: (value1, value 2, value3)}看起来像这样: d = {key1: (value1, value2, value), key2: (value1, value2, value), key3: (value1, value 2, value3)}

I want to print value1 from all of the keys.我想从所有键打印 value1。 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.我还想找到所有键中的最高 value2,以及所有键中 value3 的平均值。 Can someone please help me with this?有人可以帮我解决这个问题吗?

You can use for loop to iterate:您可以使用for loop进行迭代:

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:您可以将您的 dict 转换为 DataFrame,这将使您的工作变得非常容易:

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

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

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