如何使用元组迭代字典?

时间:2019-10-20 20:53:03

标签: python dictionary tuples iteration

因此,我需要遍历python中的字典,其中的键是一个元组,值是整数。 我只需要打印出键和值。 我尝试过:

for key,value in dict:

但是没有用,因为它将元组的第一个元素分配给键和值,并将第二个元素分配给值。

那我应该怎么做?

4 个答案:

答案 0 :(得分:0)

尝试类似的东西:

for item in a_dict.items():
   print(item)

您会看到它打印出一个作为键和值的元组,item [0]应该是您的touble,item [1]应该是该键下存储的值。

答案 1 :(得分:0)

您对for key,value in dict同时遍历键和值的假设是错误的。 您需要

for key in dict:
    print("key: " + key)
    print("value: " + dict[key])

或者如果您喜欢:

for key,value in dict.items():
    print("key: " + key)
    print("value: " + value)

如果您需要元组中的两个键,也可以进行

for (key1, key2),value in dict.items():
    print("key1: " + key1)
    print("key2: " + key2)
    print("value: " + value)

答案 2 :(得分:0)

只需使用 for key in dict 然后使用dict [key]

访问该值

答案 3 :(得分:0)

# regarding a proposed edit:
# dict() can be used to initialize a dict from different formats
# it accepts for instance a dict or a list of tuples
# in case of a static dict like below, only using {..} is sufficient
dot = dict({
  ('a', 'b'): 1,
  ('c', 'd'): 2
})

for k, v in dot.items():
   print(k,  " and ", v)