【问题标题】:Get all values from each key从每个键中获取所有值
【发布时间】:2016-10-28 13:34:40
【问题描述】:

我刚刚了解到:

coloring_dictionary = {}
coloring_dictionary.setdefault(key, [])
coloring_dictionary[key].append(1)
coloring_dictionary[key].append(77)
coloring_dictionary[key].append(3)

会给我一个带有一个键的字典,它映射到三个值(我的项目中需要这个!)。伟大的。现在我想访问每个键的每个值并对其执行一些操作(在这种情况下只有一个键,但这也适用于多个键。)

我应该如何编写我的 for 循环以逐个获取每个值? 这是我目前所拥有的:

for key in coloring_dictionary.keys():
    for the_value in coloring_dictionary[key]:
        print(coloring_dictionary[]????)  #here I want to access A value  
        #do some operations on a value 

这可能是一个简单的答案,但我被困住了。在此先感谢我的 SO 社区同胞!

【问题讨论】:

  • 顺便说一句,你也可以使用 collections.defaultdict 代替 setdefault -> coloring_dictionary = defaultdict(list)
  • 你真的在问如何迭代列表吗?
  • 感谢您为建设性回答 Pad 付出的努力。

标签: python dictionary key


【解决方案1】:

变量the_value 应该包含您要查找的值

for key in coloring_dictionary.keys():
    for the_value in coloring_dictionary[key]:
        print(the_value)  # As simple as that 

解释你在做什么:

你的字典看起来像这样:

 coloring_dictionary = {
     "key1": [1,2,3,4],
     "key2": [5,6,7,8]
 }

在外部循环中,您正在遍历该字典的所有键,因此变量 key 首先包含“key1”,然后包含“key2”。

在内部循环中,您将遍历字典在key 位置保存的所有值。在“key1”的情况下,它们是 1、2、3 和 4。它们存储在 the_value

【讨论】:

  • 谢谢莫里斯。真的很简单,但这可能有一天会帮助其他人!
【解决方案2】:

例如,如果您想将值乘以 2,然后重新分配/更新字典:

for key in coloring_dictionary:
    coloring_dictionary[key] = coloring_dictionary[key] * 2

一般:

def some_function(dictionary_input):
     #Do some stuff to value and save to dictionary_input
     return dictionary_input

for key in coloring_dictionary:
    coloring_dictionary[key] = some_function(coloring_dictionary[key])

【讨论】:

  • 谁在发帖半秒后对我投了反对票,请解释一下咳咳其他发帖的人
  • 我为什么要这样做?
猜你喜欢
  • 2018-03-02
  • 2012-08-04
  • 2014-10-03
  • 1970-01-01
  • 2013-02-07
  • 2016-06-02
  • 2011-11-15
  • 2021-08-26
  • 2017-04-03
相关资源
最近更新 更多