一种从无序字典保证键/值表排序的方法?

2024-05-19 17:38:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含数据的字典和标题。有没有一种方法可以将这些数据分成两个列表,同时保持从字典中提取的顺序?我必须分别处理键列表和值列表,然后使用这些列表构建字符串。在

这很重要,因为我单独打印出来,输出必须匹配。与输入时相比,列表是否无序并不重要。只要他们在名单上的位置匹配,就可以了。在

下面是一个非常简单的例子来说明这个案例:

mydict = {'Hello':1, 'World':2, 'Again':3}
keys = mydict.keys()
values = mydict.values()

print 'The list of keys are: %s' % stringify(keys)
print 'The corresponding values are: %s' % stringify(values)

# Output:
> The list of keys are: Hello, Again, World
> The corresponding values are: 1, 3, 2

我知道我可以建立一个有序的字典,然后得到键/值的排序将得到保证,但我也希望处理这种情况(非排序字典)。在


Tags: ofthe数据hello列表world字典keys
3条回答

{{1}如果你总是在cdm>中看到任意顺序的<1},那么你将始终看到<1}>的顺序。从docs

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). The same relationship holds for the iterkeys() and itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. Another way to create the same list is pairs = [(v, k) for (k, v) in d.iteritems()].

titles = myDict.keys()
allData = [myDict[t] for t in titles]

这样,titles的顺序可能不可预测,但是{}中的每个元素都是属于{}中相应元素的数据

只需使用items,这将有效地为您提供keys和{}的压缩副本:

items = mydict.items()

print 'The list of keys are: %s' % stringify([key for key, value in items])
print 'The list of values are: %s' % stringify([value for key, value in items])

相关问题 更多 >