简体   繁体   English

如何在python中的字典中遍历键和值

[英]how to iterate through keys and values in a dictionary in python

I have created a dictionary which has data like this: 我创建了一个字典,其中包含以下数据:

0 = {'Input_file': 'Sample_ Data.xlsx', 'Column_Name': 'Status', 'Column_Filter': 'Active'}

1 = {'Input_file': 'Sample_ Data.xlsx', 'Column_Name': 'Status', 'Column_Filter': 'Inactive'}

how can I iterate through only the values in the same order as 0 and 1 without the keys getting printed. 我如何只遍历与0和1相同顺序的值而又不打印键。 I want to read :- Sample_Data.xlsx , Status, Active in the first iteration and Sample_Data.xlsx , Status, Inactive in the second. 我想阅读: Sample_Data.xlsx , Status, Active在第一次迭代中Sample_Data.xlsx , Status, InactiveSample_Data.xlsx , Status, Inactive在第二次迭代中Sample_Data.xlsx , Status, Inactive

Below is the code I am using to print. 以下是我用于打印的代码。

my_dict = reference.to_dict('index')
for column,values in my_dict.items():
    print("{} = {}".format(column, values))

You can use list(dict.keys()) to get the keys as a list. 您可以使用list(dict.keys())来获取密钥作为列表。 As N_tro_P pointed out, you can use sorted(dict.keys()) to get keys in sorted order and iterate with that. 正如N_tro_P所指出的那样,您可以使用sorted(dict.keys())来获取已排序键,并对其进行迭代。

There is no guaranteed "order" for dictionary. 字典没有保证的“顺序”。 However, since both dictionaries have the same keys you could cycle through one and use the key against both (or other dictionaries as well). 但是,由于两个字典都具有相同的键,因此您可以循环浏览一个,并针对两个(或其他字典)使用该键。 When you "iterate" a dictionary in Python you get the key. 当您“迭代” Python中的字典时,您会得到密钥。 Use the key to access the values of the "other" dictionaries. 使用键访问“其他”词典的值。

for keys in my_dict
   print(my_dict[key])
   print(my_other_dict[key])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM