获取每个键的所有值

时间:2016-10-28 13:34:41

标签: python dictionary key

我刚刚了解到:

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社区!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

例如,如果要将值乘以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])