2017-03-03 234 views
-4

我想合并两个我有的列表。将两个字典合并为一个结果字典

gpbdict = dict(zip(namesb, GPB)) 
>>> {'1': True, '3': True, '2': True, '5': True, '4': True, '7': True, '6': True, '8': True} 
gpadict = dict(zip(namesa, GPA)) 
>>> {'11': True, '10': True, '13': True, '12': True, '15': True, '14': True, '16': True, '9': True} 

但是,它似乎并不简单到只是:

json.loads(gpadict + gpbdict) 

gpa_gpb = [gpadict, gpbdict] 
print json.dumps(gpa_gpb, indent=2, sort_keys=True)) 
只是稍后

会产生一个结果有两个单独的列表:

>>>[ 
>>> { 
>>> "10": true, 
>>> "11": true, 
>>> "12": true, 
>>> "13": true, 
>>> "14": true, 
>>> "15": true, 
>>> "16": true, 
>>> "9": true 
>>> }, 
>>> { 
>>> "1": true, 
>>> "2": true, 
>>> "3": true, 
>>> "4": true, 
>>> "5": true, 
>>> "6": true, 
>>> "7": true, 
>>> "8": true 
>>> } 
>>>] 

有没有我失踪的一步?

+2

[如何在单个表达式中合并两个Python字典?](http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-表情) – mkrieger1

+0

你可以通过谷歌轻松找到这个问题的答案。 Veeeeery容易。你也应该学习更多关于Python术语的知识。 –

+0

@anandtripathi小心!字典上的'update'方法不*返回任何东西。但是你评论的本质是真实有效的。 – MariusSiuram

回答

3

你正在做一些奇怪的事情。

首先,你想合并Python对象,不是吗?为什么以及如何? gpbdictgpbadict都是字典(不是list),所以你的问题不是很具体。预计json.loads会收到一个字符串(一个JSON)而不是一个Python对象。所以,也许你只是想:

gpbadict = dict(zip(namesb + namesa, GPB + GPA)) 

注意+工程确定与名单,但不使用词典的运营商。

如果要合并的词典,在另一方面,你可以使用update

gpadict.update(gpbdict) 

这将有效地合并词典:gpadict将成为双方gpadict(起始之一)的组合和gpbdict。如果有重复的密钥,它们将被覆盖。

而在整个问题中,我找不到任何真正的JSON参考。我错过了什么?