将字典追加到嵌套字典

时间:2018-06-29 13:21:11

标签: python dictionary

我的两个字典看起来像

d1={123456 :{u'xyz':u'987'}, 892019:{u'kjl':u'0902'}, 102930491:{u'plm':u'019240',u'kop':u'09829'}}
d2= {u'random_no_1': [u'123456', u'892019'], u'random_no_2': [u'102930491']}

我想要一本组合字典。像这样的东西。

d3 = {'random_no_1':{123456:{xyz:987}, 892019:{kjl:0902}}, 'random_no_2':{102930491:{plm:019240,kop:09829}}

我尝试了这个循环,但是它只会首先打印到键上。

result = {}
for k, v in d1.items():
  if isinstance(v, list):
     result[k] = {k: d2.get(k) for k in v}
  else:
      result[k] = {v: d2.get(v)}

所以我的结果看起来像这样。

result = {'random_no_1':{123456 : None}, 892019: None}, 'random_no_2':{102930491: None} 

我认为问题出在循环中,任何建议将不胜感激。

4 个答案:

答案 0 :(得分:0)

您可以单线完成

result = {key: {val: d1.get(val) for val in d2[key]} for key in d2}

答案 1 :(得分:0)

使用迭代&dict()

演示:

d1={123456 :{"xyz":987}, 892019:{"kjl":902}, 102930491:{"plm":19240,"kop":9829}}
d2= {'random_no_1': [123456, 892019], '3.9.1.3': [102930491]}

d3 = {}
for k,v in d2.items():
    d3[k] = {}
    for i in v:
        d3[k][i] = d1.get(i)
print(d3)

或单线

d3 = dict((k, {i: d1.get(i) for i in v}) for k,v in d2.items())

输出:

{'random_no_1': {123456: {'xyz': 987}, 892019: {'kjl': 902}}, '3.9.1.3': {102930491: {'kop': 9829, 'plm': 19240}}}

答案 2 :(得分:0)

您可以尝试

>>> d1
{123456: {u'xyz': u'987'}, 102930491: {u'kop': u'09829', u'plm': u'019240'}, 892019: {u'kjl': u'0902'}}
>>> d2
{u'random_no_2': [u'102930491'], u'random_no_1': [u'123456', u'892019']}
>>> {key:value for key,value in d2.iteritems()}
{u'random_no_2': [u'102930491'], u'random_no_1': [u'123456', u'892019']}
>>> {key:[item for item in value] for key,value in d2.iteritems()}
{u'random_no_2': [u'102930491'], u'random_no_1': [u'123456', u'892019']}
>>> {key:[d1.get(int(item)) for item in value] for key,value in d2.iteritems()}
{u'random_no_2': [{u'kop': u'09829', u'plm': u'019240'}], u'random_no_1': [{u'xyz': u'987'}, {u'kjl': u'0902'}]}

答案 3 :(得分:-1)

您可以对itertools.groupby使用嵌套词典理解:

import itertools
d1={123456 :{u'xyz':u'987'}, 892019:{u'kjl':u'0902'}, 102930491:{u'plm':u'019240',u'kop':u'09829'}}
d2= {u'random_no_1': [u'123456', u'892019'], u'random_no_2': [u'102930491']}
def sort_key(x):
  return [a for a, b in d2.items() if str(x[0]) in b][0]

new_d = [[a, list(b)] for a, b in itertools.groupby(sorted(d1.items(), key=sort_key), key=sort_key)]
last_d = {a:dict(b) for a, b in new_d}

输出:

{'random_no_1': {123456: {'xyz': '987'}, 892019: {'kjl': '0902'}}, 'random_no_2': {102930491: {'plm': '019240', 'kop': '09829'}}}