2017-04-18 121 views
0

下面是来自类似输入的大文件的示例输入。如何合并两个词典与Python中的字典?

{ 
    "V-Su7890": [ 
     [ 
      { 
       "url": "www.talent.com", 
       "tid": "V-Su7890", 
       "id": "58ff787ffbad487b2c", 
       "company_name": "Talent Ltd" 
      } 
     ], 
     [ 
      { 
       "socials": ["facebook", "linkedin", "twitter"], 
       "title": "title of the pag", 
       "contact": ["+9563802140"], 
       "email": "email_id1" 
      }, 
      { 
       "socials": ["facebook", "twitter", "linkedin"], 
       "title": "next title of the page", 
       "contact": ["+919765983442"], 
       "email": "email_id2" 
      } 
     ] 
    ] 
} 

我不得不当前词典的第二列表的所有分字典合并成一个字典没有重复的值,然后存入字典作为一个值键“V-Su7890”。

所需的输出是:

{ 
    "V-Su7890": [ 
     [ 
      { 
       "url": "www.talent.com", 
       "tid": "V-Su7890", 
       "id": "58ff787ffbad487b2c", 
       "company_name": "Talent Ltd" 
      } 
     ], 
     [ 
      { 
       "socials": ["facebook", "linkedin", "twitter"], 
       "title": ["title of the pag", "next title of the page"], 
       "contact": ["+9563802140", "+919765983442"], 
       "email": ["email_id","email_id2"] 
      } 
     ] 
    ] 
} 

请帮助我了解和解决这个问题。

+0

你尝试过什么到目前为止并在运行什么问题到? – pvg

回答

1

您可以使用setdefault()以默认值插入关键(在这里你可以使用空表),并extend列表,如果新项目不存在。

for k,v in a.items(): 
    tmp={} 
    for i in v[1]: 
     for k1,v2 in i.items(): 
      if isinstance(v2,list): 
       tmp.setdefault(k1,[]).extend(i for i in v2 if i not in tmp[k1]) 
      else: 
       tmp.setdefault(k1,[]).append(v2) 
    a[k]=[v[0],[tmp]] 
print(a) 

结果:

{ 
    'V-Su7890': [ 
    ... 
    [ 
     { 
     'contact': ['+9563802140','+919765983442'], 
     'socials': ['facebook','linkedin','twitter'], 
     'email': ['email_id1','email_id2'], 
     'title': ['title of the pag','next title of the page'] 
     } 
    ] 
    ] 
} 
+0

谢谢,但是,这也将下一个记录结合到以前的字典中。例如,{“V-Su7890”:[..................],''V-SZ86385ZM':[............ ..]},'email'中的值包含重复项。 – Niveram

+0

@Niveram我编辑我的答案,将'tmp = {}'放在for循环中,并且它不会合并下一条记录。 – McGrady

+0

很好..谢谢麦格雷迪。 – Niveram

0

假设你存储完整dict在一个变量V.我们为socialstitle等存储在一组值,以避免出现重复的值。稍后,我们会将这些设置转换为列表。这里的解决方案:

V = k["V-Su7890"][1] 
new_dict = {} 

for v in V: 
    for key, value in v.iteritems(): 
     if not new_dict.get(key, None): 
      new_dict[key] = set() 

     if isinstance(value, list): 
      for val in value: 
       new_dict[key].add(val) 
     else: 
      new_dict[key].add(value) 

# Converting the sets to list 
for key, value in new_dict.iteritems(): 
    new_dict[key] = list(value) 

k["V-Su7890"][1] = [new_dict] 
+0

对不起,我有疑问。什么是V = k [“V-Su7890”] [1]?你提到“存储完整的字典在一个变量V”,但该文件只包含字典列表,因为我已经在上面采样了 – Niveram

+0

你已经把原始的dict列表包含在大括号内,这本身就是一个字典。 {“V-Su7890”:[...] – Charul