Python字典-使用相同的键添加新字典,而不删除最后一个

时间:2019-01-04 14:12:46

标签: python

一个我想做的简单例子:

我有两个(或更多)具有相同键的字典:

a = {"animal" : "elefant"}
b = {"animal" : "dog"}

并且我想有一个包含这两者的新字典,如下所示:

c = { {"animal" : "elefant"}, {"animal" : "dog"} }

当然,我有多个词典,我想将它们添加到一个大词典中,例如在for循环中。

我不想将所有值映射到一个键,也许它不是字典的字典,而是字典的列表? (这就是我问的原因。)

2 个答案:

答案 0 :(得分:0)

您可以使用> scrypt@6.0.3 preinstall /home/user/code/project/api_v0.8/node_modules/scrypt > node node-scrypt-preinstall.js > scrypt@6.0.3 install /home/user/code/project/api_v0.8/node_modules/scrypt > node-gyp rebuild gyp ERR! configure error gyp ERR! stack Error: EACCES: permission denied, mkdir '/home/user/code/project/api_v0.8/node_modules/scrypt/build' gyp ERR! System Linux 4.20.0-042000-generic gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /home/user/code/project/api_v0.8/node_modules/scrypt gyp ERR! node -v v9.11.2 gyp ERR! node-gyp -v v3.8.0 gyp ERR! not ok npm WARN api_v0.8@1.0.0 No repository field. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! scrypt@6.0.3 install: `node-gyp rebuild` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the scrypt@6.0.3 install script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. 将同一键映射到多个值:

collections.defaultdict()

如果您想将相同的词典一起放在嵌套列表中:

from collections import defaultdict

a = {"animal" : "elefant"}
b = {"animal" : "dog"}

d = defaultdict(list)
d["animal"].append(a["animal"])
d["animal"].append(b["animal"])

print(d)
# defaultdict(<class 'list'>, {'animal': ['elefant', 'dog']})

或者您可以使用itertools.groupby()

from collections import defaultdict

lst = [{"animal": "elefant"}, {"animal": "dog"}, {"human": "John"}, {"human": "Jane"}]

data = defaultdict(list)
for dic in lst:
    k = tuple(dic)[0]
    data[k].append(dic)

print(list(data.values()))
# [[{'animal': 'elefant'}, {'animal': 'dog'}], [{'human': 'John'}, {'human': 'Jane'}]]

答案 1 :(得分:-1)

您可以使用扩展或更新方法:

first = {1: 1, 2: 2}
second = {2: 'ha!', 3: 3}
first.update(second)

输出:

first:
{1: 1, 2: 'ha!', 3: 3}

这是默认设置,但是可以通过不同的方式实现,以将词典转换为词典词典

编辑:

def update_without_overwriting(d, x):
    dict.update({k: v for k, v in x.items() if k not in d})

解决任何潜在的覆盖问题