【问题标题】:Merging two dictionaries into a resultant dictionary将两个字典合并成一个结果字典
【发布时间】:2017-07-23 10:34:02
【问题描述】:

我正在尝试合并我拥有的两个列表。

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
>>>  }
>>>]

有没有我遗漏的步骤?

【问题讨论】:

  • 你可以通过谷歌轻松找到这个问题的答案。很容易。此外,您应该了解更多有关 Python 术语的信息。
  • @anandtripathi 注意! update 字典上的方法确实返回任何东西。但你评论的本质是真实有效的。
  • 这与 JSON 或列表无关。
  • 我意识到我们无法编辑评论,所以我不得不删除 @MariusSiuram 抱歉给您带来的不便

标签: python json dictionary merge


【解决方案1】:

你在做一些奇怪的事情。

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

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

请注意,运算符 + 可以用于列表,但不能用于字典。

另一方面,如果你想合并字典,你可以使用update:

gpadict.update(gpbdict)

这将有效地合并字典:gpadict 将成为gpadict(起始)和gpbdict 的组合。如果有重复的键,它们将被覆盖。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 2012-09-17
    • 2021-09-03
    • 2022-06-10
    • 2019-05-16
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多