简体   繁体   English

遍历python字典吗?

[英]Iterating over a python dictionary?

I have a dictionary where the keys are integers and the values are strings. 我有一本字典,其中的键是整数,值是字符串。 The dictionary has been sorted using key values. 该词典已使用键值进行了排序。 I need to copy the corresponding string values (keeping the sorted order) to a list. 我需要将相应的字符串值(保持排序顺序)复制到列表中。 I cannot figure out how to iterate over the dictionary. 我不知道如何遍历字典。

I know the number of key-value pairs in the dictionary (let it be 'n'). 我知道字典中键/值对的数量(让它为“ n”)。

    Some_ordered_dict
    resultant_list=[]
    for i in range(n):
        resultant_list.append(Some_ordered_dict[increment-key?]

The dictionary was sorted using OrderedDict from some dictionary 'dic' as follows; 字典是使用OrderedDict从某些字典“ dic”中排序的,如下所示;

    od=collections.OrderedDict(sorted(dic.items()))

The essential point is that I have to display the strings values of the dictionary in the same order as they appear in the sorted dictionary. 重要的一点是,我必须按照与已排序字典中出现的顺序相同的顺序显示字典的字符串值。

resultant_list = [d[k] for k in sorted(d)]

The standard Python dictionary does not guarantee that items in a dictionary will be kept in any order. 标准的Python字典不保证字典中的项目将以任何顺序保留。 Next thing is that you have to iterate using a "for in" statement like such: 接下来的事情是,您必须使用“ for in”语句进行迭代,如下所示:

Some_ordered_dict
    resultant_list=[]
    for i in Some_ordered_dict:
        resultant_list.append(Some_ordered_dict[i])

You should take a look at the ordered dict collection to ensure that the items on your dict are kept in the order that you expect. 您应该查看订购的字典集合,以确保字典上的项目按期望的顺序保留。

Using the standard unordered dictionary in python you could use something like this: 在python中使用标准的无序字典,您可以使用如下代码:

resultant_list = []
for i in sorted(dict.keys()):
    resultant_list.append(dict[i])

As mentioned in other posts, dictionaries do not guarantee order. 如其他职位所述,词典不保证顺序。 One way to get a sorted list would be to created a list of tuples out of your dict's (key, value) pairs, then sort this list based n the first element(the key), as follows: 获取排序列表的一种方法是从dict的(键,值)对中创建一个元组列表,然后基于第一个元素(键)对该列表进行排序,如下所示:

my_dict = {2: 'two', 3: 'three', 1: 'one'}
my_tuple_list = list(zip(my_dict.keys(), my_dict.values()))
my_sorted_list = sorted(my_tuple_list, key = lambda item: item[0])
resultant_list = [x[1] for x in my_sorted_list]

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

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