Mec*_*ail 114 python dictionary associative-array idioms set-operations
你如何计算dictPython 中两个对象的并集,其中(key, value)结果中存在一对iff key是indict(除非有重复)?
例如,{'a' : 0, 'b' : 1}和{'c' : 2}的结合{'a' : 0, 'b' : 1, 'c' : 2}.
您最好不要修改任何输入dict.这有用的示例:获取当前范围内所有变量及其值的字典
Mec*_*ail 98
这个问题提供了一个成语.您使用其中一个dicts作为dict()构造函数的关键字参数:
dict(y, **x)
Run Code Online (Sandbox Code Playgroud)
解决重复项以支持其中的值x; 例如
dict({'a' : 'y[a]'}, **{'a', 'x[a]'}) == {'a' : 'x[a]'}
Run Code Online (Sandbox Code Playgroud)
Nil*_*esh 84
你也可以使用update像dict的方法
a = {'a' : 0, 'b' : 1}
b = {'c' : 2}
a.update(b)
print a
Run Code Online (Sandbox Code Playgroud)
Mat*_*ose 26
两本词典
def union2(dict1, dict2):
return dict(list(dict1.items()) + list(dict2.items()))
Run Code Online (Sandbox Code Playgroud)
n字典
def union(*dicts):
return dict(itertools.chain.from_iterable(dct.items() for dct in dicts))
Run Code Online (Sandbox Code Playgroud)
如果您需要两个dicts保持独立和可更新,您可以创建一个单独的对象,在其__getitem__方法(和实现 get,__contains__以及您需要的其他映射方法)中查询字典.
极简主义的例子可能是这样的:
class UDict(object):
def __init__(self, d1, d2):
self.d1, self.d2 = d1, d2
def __getitem__(self, item):
if item in self.d1:
return self.d1[item]
return self.d2[item]
Run Code Online (Sandbox Code Playgroud)
它有效:
>>> a = UDict({1:1}, {2:2})
>>> a[2]
2
>>> a[1]
1
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in __getitem__
KeyError: 3
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57152 次 |
| 最近记录: |