【问题标题】:How to iterate over a dictionary with tuples? [duplicate]如何用元组遍历字典? [复制]
【发布时间】:2020-02-17 00:10:20
【问题描述】:

所以,我需要在 python 中迭代一个字典,其中键是元组,值是整数。 我只需要打印出键和值。 我试过这个:

for key,value in dict:

但不起作用,因为它将元组的第一个元素分配给键和值,将第二个元素分配给值。

那我该怎么做呢?

【问题讨论】:

  • 请。显示一些数据。

标签: python dictionary tuples iteration


【解决方案1】:

您认为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】:

    尝试类似:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:
        # 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)
        

        【讨论】:

          猜你喜欢
          • 2018-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-07
          • 2019-12-17
          相关资源
          最近更新 更多