【问题标题】:How to print one specific value from each key in a dictionary in Python?如何从 Python 字典中的每个键打印一个特定值?
【发布时间】:2020-09-16 07:56:04
【问题描述】:

我有一个由 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])

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

【问题讨论】:

标签: python dictionary key key-value


【解决方案1】:

可以使用for loop进行迭代:

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

【讨论】:

    【解决方案2】:

    怎么样?

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

    【讨论】:

      【解决方案3】:

      试试这个兄弟:

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

      【讨论】:

        【解决方案4】:

        您可以将您的 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
        

        【讨论】:

          【解决方案5】:

          您可以使用列表理解来实现:

          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
          

          【讨论】:

          • 您还知道如何打印 value1 的最大值 2 吗?因此,由于在您的示例中 max value2 为 8,python 会从该键打印值 1 (7)?
          • @SiljeBue 很高兴我能提供帮助。如果您觉得它有帮助,如果您支持并使其接受答案(如果它确实回答),将不胜感激。谢谢。
          猜你喜欢
          • 2021-08-19
          • 1970-01-01
          • 1970-01-01
          • 2020-12-28
          • 2017-07-19
          • 2012-03-09
          • 1970-01-01
          • 1970-01-01
          • 2015-12-23
          相关资源
          最近更新 更多