多个赋值到一个python字典中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21222506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple assignments into a python dictionary
提问by ozi
Is it possible to assign values to more than one keys of a dictionary in a more concise way than the one below?
是否有可能以比下面更简洁的方式为字典的多个键赋值?
I mean, let dbe a dictionary initialized as below:
我的意思是,让d字典初始化如下:
d={'a':1,'b':2,'c':3}
To assign values to multiple keys I need to do this:
要将值分配给多个键,我需要这样做:
d['a']=10
d['b']=200
d['c']=30
Can I achieve same with something like this:
我可以用这样的东西来达到同样的目的:
d['a','b','c']=10,200,30
Thanks.
谢谢。
采纳答案by Aamir Adnan
You can use dict.update:
您可以使用dict.update:
d.update({'a': 10, 'c': 200, 'c': 30})
This will overwrite the values for existing keys and add new key-value-pairs for keys that do not already exist.
这将覆盖现有键的值并为尚不存在的键添加新的键值对。
回答by ChrisProsser
You could use a dictionary comprehension e.g.
您可以使用字典理解,例如
letters, nos = ['a','b','c'], [1,2,3]
d = {letters[i]: nos[i] for i in range(len(nos))}
output:
输出:
{'a': 1, 'c': 3, 'b': 2}
{'a':1,'c':3,'b':2}
回答by abarnert
You can always wrap it in a function:
您始终可以将其包装在一个函数中:
def multiassign(d, keys, values):
d.update(zip(keys, values))
Even if you didn't know about update, you could write it like this:
即使你不知道update,你也可以这样写:
def multiassign(d, keys, values):
for k, v in zip(keys, values):
d[k] = v
Or you can even write a dictsubclass that gives you exactly the syntax you wanted:
或者您甚至可以编写一个dict子类,为您提供所需的语法:
class EasyDict(dict):
def __getitem__(self, key):
if isinstance(key, tuple):
return [super().__getitem__(k) for k in key]
else:
return super().__getitem__(key)
def __setitem__(self, key, value):
if isinstance(key, tuple):
self.update(zip(key, value))
else:
super().__setitem__(key, value)
def __delitem__(self, key, value):
if isinstance(key, tuple):
for k in key: super().__delitem__(k)
else:
super().__setitem__(key, value)
Now:
现在:
>>> d = {'a': 1, 'd': 4}
>>> multiassign(d, ['a', 'b', 'c'], [10, 200, 300])
>>> d
{'a': 10, 'b': 200, 'c': 300, 'd': 4}
>>> d2 = EasyDict({'a': 1, 'd': 4})
>>> d2['a', 'b', 'c'] = 100, 200, 300
>>> d2
{'a': 10, 'b': 200, 'c': 300, 'd': 4}
Just be aware that it will obviously no longer be possible to use tuples as keys in an EasyDict.
请注意,显然不再可能将元组用作EasyDict.
Also, if you were going to use this for something serious, you'd probably want to improve the error handling. (d['a', 'b'] = 1will give a cryptic message about zip argument #2 must support iteration, d['a', 'b', 'c'] = 1, 2will silently work and do nothing to c, etc.)
此外,如果您打算将其用于严肃的事情,您可能希望改进错误处理。(d['a', 'b'] = 1会给出一个关于 的神秘信息zip argument #2 must support iteration,d['a', 'b', 'c'] = 1, 2会默默地工作,什么也不做c,等等)
回答by Delgan
You can also simply use the multiple assigment semantics:
您也可以简单地使用多重赋值语义:
d['a'], d['b'], d['c'] = 10, 200, 30
回答by Sklavit
A speed comparison, from the worst to the best:
速度比较,从最差到最好:
Python 3.5.3 |Continuum Analytics, Inc.| (default, May 15 2017, 10:43:23) [MSC v.1900 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import numpy.random as nprnd
...: d = dict([(_, nprnd.rand()) for _ in range(1000)])
...: values = nprnd.randint(1000, size=10000)
...: keys = nprnd.randint(1000, size=10000)
...: def multiassign(d, keys, values):
...: for k, v in zip(keys, values):
...: d[k] = v
...:
...: d1 = dict(d)
...: %timeit multiassign(d1, keys, values)
...: d1 = dict(d)
...: %timeit {**d1, **{keys[i]: values[i] for i in range(len(keys))}}
...: d1 = dict(d)
...: %timeit d1.update(zip(keys, values))
...: d1 = dict(d)
...: %timeit {*d1.items(), *zip(keys, values)}
...: d1 = dict(d)
...: %timeit {**d1, **{key: value for key, value in zip(keys, values)}}
...: d1 = dict(d)
...: %timeit {**d1, **dict(zip(keys, values))}
4 ms ± 25.6 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.66 ms ± 29.9 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.17 ms ± 31.1 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.81 ms ± 98.3 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.38 ms ± 75.8 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
1.96 ms ± 21 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
So the clear winner is recreation of dictionary from dictionaries.
所以明显的赢家是从字典中重新创建字典。

