【问题标题】:How To Print A Key In A Dictionary With A For Loop如何使用 For 循环打印字典中的键
【发布时间】:2022-01-12 20:13:06
【问题描述】:

如何在 for 循环中打印出字典的键?使用下面的代码,我知道如何打印字典的值“2、3、4、5”,但我将如何打印键“1”?

dictionary = {}
nums = "1 2 3 4 5"
splitList = nums.split()
dictionary[splitList[0]] =[(splitList[1]), (splitList[2]), (splitList[3]), (splitList[4])]

print(dictionary)

for i in dictionary:
    print(dictionary[i])
    print(dictionary[i][1])
#How do I print the key?

【问题讨论】:

  • i 是关键。
  • 是的,只需 print(i) 打印密钥。

标签: python dictionary


【解决方案1】:

供参考:

#Assume we have some dictionary named dict

for key in dict.keys():
    print(key) #prints the keys of the dict

for value in dict.values():
    print(value) #prints the values of the dict

for key, value in dict.items():
    print(key, value) #prints the keys and values of the dict

有关 Python 字典的更多信息,请参阅https://python-reference.readthedocs.io/en/latest/docs/dict/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2021-08-04
    • 1970-01-01
    • 2018-08-07
    • 2019-02-22
    相关资源
    最近更新 更多