![](/img/trans.png)
[英]How to create a new key in dictionary with value from another key list from a list of dictionary in Python?
[英]Create python dictionary from value of another dictionary?
我试图从另一个字典的键值有效地构造一个python字典。
例如...
dict1 = {'foo': [1, 3, 7], 'bar': [2, 4, 8]} ## note: all values in {key: value} will be unique
## Algorithm here...
dict2 = {1: [3, 7], 3: [1, 7], 7: [1, 3], 2: [4, 8], 4: [2, 8], 8: [2, 4]}
我可以通过蛮力方法获得此结果,但这些词典适用于节点数超过100000的图形,因此我需要这样做才能提高效率。
任何帮助将不胜感激。
这是我的处理方式:
dict2 = {k: x[:i] + x[i+1:] for x in dict1.values() for i, k in enumerate(x)}
如果您使用的是Python 2.x,则可能要使用dict1.itervalues()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.