python Python字典添加新键值对的简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1721795/
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
Python dictionary simple way to add a new key value pair
提问by Lakshman Prasad
Say you have,
说你有,
foo = 'bar'
d = {'a-key':'a-value'}
And you want
你想要
d = {'a-key':'a-value','foo':'bar'}
e = {'foo':foo}
I know you can do,
我知道你可以做到
d['foo'] = foo
#Either of the following for e
e = {'foo':foo}
e = dict(foo=foo)
But, in all these way to add the variable foo to dict, I have had to use the word foo
twice; once to indicate the key and once for its value.
但是,在所有这些将变量 foo 添加到 dict 的方法中,我不得不使用这个词foo
两次;一次表示键,一次表示其值。
It seems wasteful to me to use foo
twice. Is there a simpler way, in which you can tell python "Add this variable to the dictionary with its name as the key and its value as the value"?
使用foo
两次对我来说似乎很浪费。有没有一种更简单的方法,您可以告诉python “将此变量添加到字典中,名称为键,值为值”?
回答by Anurag Uniyal
you can do something like this
你可以做这样的事情
def add_dry_foo(d, namespace, fooName):
d[fooName] = namespace[fooName]
foo = 'oh-foo'
d = {}
add_dry_foo(d, locals(), 'foo')
print d
回答by Ned Batchelder
You can use:
您可以使用:
name = 'foo'
d[name] = vars[name]
I don't see the difference between your d
and e
cases: both set 'foo' to the value of foo.
我没有看到您d
和e
案例之间的区别:都将 'foo' 设置为 foo 的值。
It gets trickier if you want to bury this in a function:
如果你想把它埋在一个函数中,它会变得更加棘手:
def add_variable(d, name):
# blah
because then it has to use inspect
to start poking around in frames.
因为那时它必须用来inspect
开始在帧中四处游荡。
This sounds like a larger problem that might have a nicer solution if you wanted to describe it to us. For example, if the problem is that you don't care just about foo, but in fact, a whole slew of local variables, then maybe you want something like:
这听起来像是一个更大的问题,如果您想向我们描述它可能有更好的解决方案。例如,如果问题是您不仅关心 foo,而且实际上关心一大堆局部变量,那么您可能想要以下内容:
d.update(locals())
which will copy the names and value of all the local variables into d
.
这会将所有局部变量的名称和值复制到d
.
回答by Nick Craig-Wood
Actutally using foo
twice is remarkably common in python programs. It is used extensively for passing on arguments eg
实际上,foo
在python程序中使用两次是非常常见的。它广泛用于传递参数,例如
def f(foo, bar):
g(foo=foo)
Which is a specialised case of the dictionary manipulations in your question.
这是您问题中字典操作的特例。
I don't think there is a way of avoiding it without resorting to magic, so I think you'll have to live with it.
我不认为有办法避免它而不诉诸魔法,所以我认为你必须忍受它。
回答by nikow
To add all the local variables to a dict you can do:
要将所有局部变量添加到字典中,您可以执行以下操作:
d.update(locals())
The same works for function calls:
这同样适用于函数调用:
func(**locals())
Note that depending on where you are locals()
might of course contain stuff that should not end up in the dict. So you could implement a filter function:
请注意,根据您所在的位置locals()
,当然可能包含不应出现在 dict 中的内容。所以你可以实现一个过滤器功能:
def filtered_update(d, namespace):
for key, value in namespace.items():
if not key.startswith('__'):
d[key] = value
filtered_update(d, locals())
Of course the Python philosophy is "explicit is better than implicit", so generally I would walk the extra mile and do this kind of stuff by hand (otherwise you have to be careful about what goes on in your local namespace).
当然,Python 的哲学是“显式优于隐式”,所以通常我会多走一步并手工完成这类事情(否则你必须小心本地命名空间中发生的事情)。
回答by Wim
If you don't want to pass all of locals()
(which may be a security risk if you don't fully trust the function you're sending the data too), a one-line answer could be this:
如果您不想全部通过locals()
(如果您不完全信任您发送数据的功能,这可能会带来安全风险),单行答案可能是这样的:
dict([ (var, locals()[var]) for var in ['foo', 'bar'] ])
dict([ (var, locals()[var]) for var in ['foo', 'bar'] ])
or in Python 3.0 this would become possible:
或者在 Python 3.0 中这将成为可能:
{ var: locals()[var] for var in ['foo', 'bar'] }
{ var: locals()[var] for var in ['foo', 'bar'] }
回答by Rod Hyde
You could use eval, although I'm not sure that I'd recommend it.
您可以使用 eval,但我不确定是否会推荐它。
>>> d = dict()
>>> foo = 'wibble'
>>> def add(d, name):
d[name] = eval(name)
>>> add(d, 'foo')
>>> d
{'foo': 'wibble'}
Edit:I should point out why I don't recommend "eval". What happens if you do something like this? (from: http://mail.python.org/pipermail/tutor/2005-November/042854.html)
编辑:我应该指出为什么我不推荐“eval”。如果你做这样的事情会发生什么?(来自:http: //mail.python.org/pipermail/tutor/2005-November/042854.html)
>>> s = "(lambda loop: loop(loop)) (lambda self: self(self))"
>>> add(d, s)
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
add(d, s)
File "<pyshell#43>", line 2, in add
d[name] = eval(name)
File "<string>", line 1, in <module>
File "<string>", line 1, in <lambda>
File "<string>", line 1, in <lambda>
...
File "<string>", line 1, in <lambda>
RuntimeError: maximum recursion depth exceeded
回答by derks
It seems to me what you are talking about is an enhancement to parameter passing functionality:
在我看来,您所谈论的是对参数传递功能的增强:
def func(*vars):
provides a tuple of ordered values without keys
提供一个没有键的有序值元组
def func(**vars):
provides a dict of key value pairs, that MUST be passed as key=valuepairs.
提供键值对的字典,必须作为键=值对传递。
def func(***vars):
WOULD PROVIDE a dict of key value pairs, passed either explicitly as key=value, or implicitly as key(a variable, literals would cause error without key=)
将提供键值对的字典,显式传递为key=value,或隐式传递为键(变量,文字会导致错误没有key=)
SO:
所以:
(x1,x2,x3) = (1,2,3)
def myfunc(***vars):
retrun vars
myfunc(x1,x2,x3)
>>> {'x1':1,'x2':2,'x3':3}
But of course, this is just wishful thinking...
不过当然,这只是一厢情愿……