相关疑难解决方法(0)

Python"扩展"为字典

哪个是用另一个字典扩展字典的最佳方法?例如:

>>> a = { "a" : 1, "b" : 2 }
>>> b = { "c" : 3, "d" : 4 }
>>> a
{'a': 1, 'b': 2}
>>> b
{'c': 3, 'd': 4}
Run Code Online (Sandbox Code Playgroud)

我正在寻找任何操作来获得这个避免for循环:

{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 }
Run Code Online (Sandbox Code Playgroud)

我希望做的事情如下:

a.extend(b)  # This does not work
Run Code Online (Sandbox Code Playgroud)

python dictionary

417
推荐指数
7
解决办法
21万
查看次数

如何在python中合并两个数据结构

我有两个复杂的数据结构(即_to和_from),我想用_from的相同实体覆盖_to的实体.我举了这个例子.

# I am having two data structure _to and _from
# I want to override _to from _from
_to = {'host': 'test',
       'domain': [
           {
               'ssl': 0,
               'ssl_key': '',
           }
       ],
       'x': {}
       }
_from = {'status': 'on',
         'domain': [
             {
                 'ssl': 1,
                 'ssl_key': 'Xpyn4zqJEj61ChxOlz4PehMOuPMaxNnH5WUY',
                 'ssl_cert': 'nuyickK8uk4VxHissViL3O9dV7uGSLF62z52L4dAm78LeVdq'
             }
         ]
         }
### I want this output
_result = {'host': 'test',
           'status': 'on',
           'domain': [
               {
                   'ssl': 1,
                   'ssl_key': 'Xpyn4zqJEj61ChxOlz4PehMOuPMaxNnH5WUY',
                   'ssl_cert': 'nuyickK8uk4VxHissViL3O9dV7uGSLF62z52L4dAm78LeVdq'
               }
           ],
           'x': {}
           }
Run Code Online (Sandbox Code Playgroud)

用例2:

_to = {'host': …
Run Code Online (Sandbox Code Playgroud)

python recursion dictionary iterator data-structures

4
推荐指数
1
解决办法
618
查看次数

Python附加Counter to Counter,就像Python字典更新一样

我有2个计数器(来自集合的计数器),我想将一个附加到另一个,而第一个计数器的重叠键将被忽略.像dic.update(python词典更新)

例如:

from collections import Counter
a = Counter(a=4, b=0, c=1)
b = Counter(z=1, b=2, c=3)
Run Code Online (Sandbox Code Playgroud)

所以类似(忽略第一个计数器的重叠键):

# a.update(b) 
Counter({'a':4, 'z':1, 'b':2, 'c':3})
Run Code Online (Sandbox Code Playgroud)

我想我总是可以将它转换成某种字典,然后将其转换回Counter,或使用条件.但我想知道是否有更好的选择,因为我在一个非常大的数据集上使用它.

python counter dictionary python-3.x python-collections

4
推荐指数
2
解决办法
1077
查看次数