![](/img/trans.png)
[英]What's the simplest way to get the highest and lowest keys from a dictionary?
[英]What's an elegant way to create a dictionary from another dictionary's keys and an array of values?
如何使用另一个字典的键和值数组创建另一个字典?
我考虑过这样做:
zipped = zip(theExistingDict.keys(), arrayOfValues)
myNewDict = dict(zipped)
但是,这并不完全有效, arrayOfValues
中的每个值都与结果字典中的任意键配对。 我无法控制arrayOfValues
哪个元素与theExistingDict.keys()
哪个键配对。
theExistingDict
看起来像这样:
{u'actual bitrate': 4, u'Suggested Bitrate': 3, u'title': 2, u'id': 1, u'game slot': 0}
arrayOfValues
看起来像这样:
1.0, u'GOLD_Spider Solitaire', u'Spider\\\\nSolitaire', 120000.0, 120000.0
所以:我希望arrayOfValues[0]
映射到game slot
(因为在字典中它的值为0)。
有没有简单而优雅的方法可以做到这一点?
正如其他人所提到的,字典中没有定义任何顺序。 python文档说:“键和值以任意顺序列出,该顺序是非随机的,在Python实现中会有所不同,并且取决于字典的插入和删除历史。”
如果您要使用将项目添加到字典中的原始顺序,则可以尝试寻找保留该顺序的字典的替代实现-例如http://www.voidspace.org.uk/python/ odict.html
由于您现有的字典本身包含有关列表中元素位置的信息:您可以这样做:
>>> exist = {u'title': 2, u'actual bitrate': 4, u'id': 1, u'game slot': 0, u'Suggested Bitrate': 3}
>>> l = [1.0, u'GOLD_Spider Solitaire', u'Spider\\nSolitaire', 120000.0, 120000.0]
>>> dict((k, l[v]) for k, v in exist.iteritems())
{u'Suggested Bitrate': 120000.0, u'game slot': 1.0, u'actual bitrate': 120000.0, u'id': u'GOLD_Spider Solitaire', u'title': u'Spider\\nSolitaire'}
或在py3k / python 2.7+中:
>>> {k: l[v] for k, v in exist.items()}
{'Suggested Bitrate': 120000.0, 'game slot': 1.0, 'actual bitrate': 120000.0, 'id': 'GOLD_Spider Solitaire', 'title': 'Spider\\nSolitaire'}
也许更像是:
from operator import itemgetter
zip( array_of_values, [ a for a, _ in sorted(existing_dict.iteritems(), key=itemgetter(1)) ] )
如果您想将索引与整数(可能与未使用的值)进行匹配,可以对其进行进一步修改...
zipped = [ (k, a) for i, a in enumerate(array_of_values) for k, v in existing_dict.iteritems() if i == v ]
new_dict = dict(zipped)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.