在Python中合并两个list字典

ath*_*ra 5 python dictionary

有两本词典

x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}
Run Code Online (Sandbox Code Playgroud)

我想要另一本字典 z,它是 x 和 y 的合并字典,这样

z = {1:['a','b','c','d','e','f'],2:['g']}
Run Code Online (Sandbox Code Playgroud)

可以做这个操作吗?我试过更新操作

x.update(y)
Run Code Online (Sandbox Code Playgroud)

但它给了我以下结果

z= {1:['d','e','f'],2:['g']}
Run Code Online (Sandbox Code Playgroud)

Sha*_*tan 8

一条线解决方案:

{ key:x.get(key,[])+y.get(key,[]) for key in set(list(x.keys())+list(y.keys())) }
Run Code Online (Sandbox Code Playgroud)

示例1:

x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}
{ key:x.get(key,[])+y.get(key,[]) for key in set(list(x.keys())+list(y.keys())) }
Run Code Online (Sandbox Code Playgroud)

输出:

{1: ['a', 'b', 'c', 'd', 'e', 'f'], 2: ['g']}

示例2:

one = {'a': [1, 2], 'c': [5, 6], 'b': [3, 4]}
two = {'a': [2.4, 3.4], 'c': [5.6, 7.6], 'd': [3.5, 4.5]}
{ key:one.get(key,[])+two.get(key,[]) for key in set(list(one.keys())+list(two.keys())) }
Run Code Online (Sandbox Code Playgroud)

输出:

{'a': [1, 2, 2.4, 3.4], 'b': [3, 4], 'c': [5, 6, 5.6, 7.6], 'd': [3.5, 4.5]}


nit*_*gar -2

如果你的项目选择Python2.7。Counter()在这种情况下可以使用:

Python 2.7.16 (default, Jun  5 2020, 22:59:21) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x={1:['a','b','c']}
>>> y={1:['d','e','f'],2:['g']}
>>> from collections import Counter
>>> Counter(x) + Counter(y)
Counter({2: ['g'], 1: ['a', 'b', 'c', 'd', 'e', 'f']})
Run Code Online (Sandbox Code Playgroud)

在 Python 3.x 中,如果运行相同的代码,您将看到:

Python 3.9.0 (v3.9.0:9cf6752276, Oct  5 2020, 11:29:23) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: x={1:['a','b','c']}

In [2]: y={1:['d','e','f'],2:['g']}

In [3]: from collections import Counter

In [4]: Counter(x) + Counter(y)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-0aa8b00837b3> in <module>
----> 1 Counter(x) + Counter(y)

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py in __add__(self, other)
    759         for elem, count in self.items():
    760             newcount = count + other[elem]
--> 761             if newcount > 0:
    762                 result[elem] = newcount
    763         for elem, count in other.items():

TypeError: '>' not supported between instances of 'list' and 'int'
Run Code Online (Sandbox Code Playgroud)

我们看一下源代码vim /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py +761

为了检查Python2.x和Python3.x之间的差异,我们将找到python2中集合的路径。要做到这一点,只需执行一个错误的调用,例如:

>>> Counter(9,1) # wrong way to call.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py", line 475, in __init__
    raise TypeError('expected at most 1 arguments, got %d' % len(args))
TypeError: expected at most 1 arguments, got 2
Run Code Online (Sandbox Code Playgroud)

然后,你看/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py

好的,现在打开这两个文件并__add__找到class Counter.

vim -d /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py +761 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py
Run Code Online (Sandbox Code Playgroud)

但我们可以在这段狙击代码中找到不同之处。

在此输入图像描述

仔细想想,你可以看出这部TypeError: '>' not supported between instances of 'list' and 'int'剧有两件重要的事情:

  • > 反映到def __gt__(self, value, /)中的方法class dict。那么让我们检查一下 python2 和 python3 之间的区别dict
  • 'list''int'。为了确保我们在这里遇到相同的类型,只需添加一行即可将其打印出来。if newcount > 0:在像这样比较行之前:
print("newcount is --> ", newcount, type(newcount))
if newcount > 0:
Run Code Online (Sandbox Code Playgroud)

你会看到这个:

在此输入图像描述

并不奇怪,对吧?我们可以比较listint他们是有道理的..

让我们快速比较一下 alistintpython 2 中的 a 。

在此输入图像描述 它返回一个True. 继续深入研究 Python3.x

在此输入图像描述

好了,现在你应该清楚是怎么回事了。要解决这个问题,应该很容易对您自己的 python 环境进行一些更改或将其提交到git在此输入图像描述

最后,你得到了两个好消息,你修复了 Python3.x 的 bug。你得到了你的结果。

在此输入图像描述

如果期望的结果是一个字典。您可以使用以下内容:

z = dict(Counter(x) + Counter(y))
Run Code Online (Sandbox Code Playgroud)

  • 我在 'list' 和 'int' 实例之间不支持 '&gt;'` (11认同)