字典中的另一个字典
问题描述:
的值替换嵌套键目前我有两个字典 我想字典中的另一个字典
d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
2:{1: 7.5,2: 6.0,3: 1.0}}
d2 = {1: 'a', 2: 'b', 3: 'c'}
expected output: {1:{'a': 2.0,'b': 1.5,'c': 5.0},
2:{'a': 7.5,'b': 6.0,'c': 1.0}}
可悲的是这两个dictionarys都充满了其他字典的值来改变内部密钥很多数据,并且需要很长时间才能在d1上迭代,并调用一个迭代d2的方法来替换d1中的键。
是否有可能在更快的时间内更改内键,值对? 我发现了一个可能性,以取代简单的字典的键:
d = {'x':1,'y':2,'z':3}
d1 = {'x':'a','y':'b','z':'c'}
d = {d1[k]:v for k,v in d.items()}
output: {'a': 1, 'c': 3, 'b': 2}
但与嵌套的字典。
所以现在我不知道如何解决我的问题。 也许你们中的一个人可以帮助我。
答
您可以使用嵌套字典理解为做到这一点:
>>> d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
... 2:{1: 7.5,2: 6.0,3: 1.0}}
>>> d2 = {1: 'a', 2: 'b', 3: 'c'}
>>> {a: {d2[k]: v for k, v in d.items()} for a, d in d1.items()}
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}}
OR,使用简单for
环路:
>>> for _, d in d1.items(): # Iterate over the "d1" dict
... for k, v in d.items(): # Iterate in nested dict
... d[d2[k]] = v # Add new key based on value of "d2"
... del d[k] # Delete old key in nested dict
...
>>> d1
{1: {'a': 2.0, 'c': 5.0, 'b': 1.5}, 2: {'a': 7.5, 'c': 1.0, 'b': 6.0}}
第二条本办法将更新原d1
字典,其中作为第一方法将创建新的dict
对象。
答
我认为答案是使用我之前遇到的字典zip。
你可以用zip解决你的问题,就像在这个答案中一样。虽然你的需要一个内在的水平,所以它稍有不同。
Map two lists into a dictionary in Python
d1 = {1:{1: 2.0,2: 1.5,3: 5.0},
2:{1: 7.5,2: 6.0,3: 1.0}}
d2 = {1: 'a', 2: 'b', 3: 'c'}
d1_edited = {} # I prefer to create a new dictionary than edit the existing whilst looping though existing
newKeys = d2.values() # e.g. ['a', 'b', 'c']
for outer in d1.keys(): # e.g. 1 on first iteration
newValues = d1[outer] # e.g. e.g. {1: 2.0,2: 1.5,3: 5.0} on first iteration
newDict = dict(zip(newKeys,newValues)) # create dict as paired up keys and values
d1_edited[outer] = newDict # assign dictionary to d1_edited using the unchanged outer key.
print d1_edited
输出
{1: {'a': 1, 'c': 3, 'b': 2}, 2: {'a': 1, 'c': 3, 'b': 2}}
+0
谢谢它的作品完美 – pat92
谢谢它的作品完美 – pat92