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

我有一个由 4 个键组成的字典,每个键有 3 个值。


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


我想从所有键打印 value1 。我现在的做法是这样的:


print (persons['1'][0])

print(persons['2'][0])

print (persons['3'][0])

print(persons['4'][0])

但我想有一种更简单的方法可以让我在一行中引用所有键?我还想找到所有键中的最高值2,以及所有键中值3的平均值。有人可以帮我解决这个问题吗?


ABOUTYOU
浏览 200回答 5
5回答

有只小跳蛙

您可以将您的字典转换为 DataFrame,这将使您的事情变得非常简单:from pandas.DataFrame import from_dictd = {'a':(1,2,3),'b':(4,5,6)}d = from_dict(d, orient='index')d[0] # print values of value1d[1].max() # max of value2d[2].mean() # mean of value3

qq_花开花谢_0

您可以使用列表理解来实现此目的:persons = {'1': (1,2,3), '2': (4,5,6), '3': (7,8,9)}# First Value'sfirst_values = " ".join([str(x[0]) for x in persons.values()])print(first_values)   # prints 1 4 7# Max of second value'smax_value2 = max([x[1] for x in persons.values()])print(max_value2)  # prints 8# Average of value3'sthird_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 value2value1_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

PIPIONE

关于什么?d = {    "key1": (1,2,3),    "key2": (3,4,5),    "key4": (5,6,8),}[ print(val[0]) for _, val in d.items()]

UYOU

关于什么?d = {    "key1": (1,2,3),    "key2": (3,4,5),    "key4": (5,6,8),}[ print(val[0]) for _, val in d.items()]

缥缈止盈

您可以使用for loop迭代:d = {'test1': (1, 2, 3), 'test2': (4, 5, 6), 'test3': (7, 8, 9)}for key in d.values():    print(key[0])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python