Python 变量作为 dict 的键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3972872/
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 variables as keys to dict
提问by atp
Is there an easier way to do this in Python (2.7)?: Note: This isn't anything fancy, like putting all local variables into a dictionary. Just the ones I specify in a list.
在 Python (2.7) 中是否有更简单的方法来做到这一点?:注意:这不是什么花哨的事情,就像将所有局部变量放入字典一样。只是我在列表中指定的那些。
apple = 1
banana = 'f'
carrot = 3
fruitdict = {}
# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?
for x in [apple, banana, carrot]:
fruitdict[x] = x # (Won't work)
采纳答案by dr jimbob
for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
回答by Greg Hewgill
The globals()function returns a dictionary containing all your global variables.
该globals()函数返回一个包含所有全局变量的字典。
>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}
There is also a similar function called locals().
还有一个类似的函数叫做locals().
I realise this is probably not exactly what you want, but it may provide some insight into how Python provides access to your variables.
我意识到这可能不是你想要的,但它可能会提供一些关于 Python 如何提供对变量的访问的见解。
Edit: It sounds like your problem may be better solved by simply using a dictionary in the first place:
编辑:听起来您的问题可以通过简单地首先使用字典来更好地解决:
fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
回答by Caleb Hattingh
If you want to bind the locations of the variables themselves, there's this:
如果你想绑定变量本身的位置,有这个:
>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> fruitdict = {}
>>> fruitdict['apple'] = lambda : apple
>>> fruitdict['banana'] = lambda : banana
>>> fruitdict['carrot'] = lambda : carrot
>>> for k in fruitdict.keys():
... print k, fruitdict[k]()
...
carrot 3
apple 1
banana f
>>> apple = 7
>>> for k in fruitdict.keys():
... print k, fruitdict[k]()
...
carrot 3
apple 7
banana f
回答by Dantalion
A one-liner is:-
单线是:-
fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))
回答by mouad
why you don't do the opposite :
为什么你不做相反的事情:
fruitdict = {
'apple':1,
'banana':'f',
'carrot':3,
}
locals().update(fruitdict)
Update :
更新 :
don't use the code above check the comment.
不要使用上面的代码检查评论。
by the way why you don't mark the vars that you want to get i don't know maybe like this:
顺便说一下,为什么你不标记你想要得到的变量,我不知道可能是这样的:
# All the vars that i want to get are followed by _fruit
apple_fruit = 1
carrot_fruit = 'f'
for var in locals():
if var.endswith('fruit'):
you_dict.update({var:locals()[var])
回答by Jim Dennis
Well this is a bit, umm ... non-Pythonic ... ugly ... hackish ...
嗯,这有点,嗯......非Pythonic......丑陋......hackish......
Here's a snippet of code assuming you want to create a dictionary of all the local variables you create after a specific checkpoint is taken:
下面是一段代码,假设您要在执行特定检查点后为您创建的所有局部变量创建一个字典:
checkpoint = [ 'checkpoint' ] + locals().keys()[:]
## Various local assigments here ...
var_keys_since_checkpoint = set(locals().keys()) - set(checkpoint)
new_vars = dict()
for each in var_keys_since_checkpoint:
new_vars[each] = locals()[each]
Note that we explicitly add the 'checkpoint' key into our capture of the locals().keys()I'm also explicitly taking a slice of that though it shouldn't be necessary in this case since the reference has to be flattened to add it to the [ 'checkpoint' ] list. However, if you were using a variant of this code and tried to shortcut out the ['checkpoint'] + portion (because that key was already inlocals(), for example) ... then, without the [:] slice you could end up with a reference to thelocals().keys()` whose values would change as you added variables.
请注意,我们明确地将 'checkpoint' 键添加到我们捕获的locals().keys()I 中,尽管在这种情况下它不是必需的,因为必须将引用展平才能将其添加到 [ 'checkpoint ' ] 列表。但是,如果您使用此代码的变体并尝试快捷方式['checkpoint'] + portion (because that key was already inlocals() , for example) ... then, without the [:] slice you could end up with a reference to thelocals().keys()`,其值会随着您添加变量而改变。
Offhand I can't think of a way to call something like new_vars.update()with a list of keys to be added/updated. So theforloop is most portable. I suppose a dictionary comprehension could be used in more recent versions of Python. However that woudl seem to be nothing more than a round of code golf.
临时我想不出一种方法来调用类似new_vars.update()要添加/更新的键列表的东西。所以for循环是最便携的。我想可以在更新的 Python 版本中使用字典理解。然而,这似乎只不过是一轮代码高尔夫。
回答by Terence Honles
This question has practically been answered, but I just wanted to say it was funny that you said
这个问题实际上已经得到了回答,但我只是想说你说的很有趣
This isn't anything fancy, like putting all local variables into a dictionary.
这不是什么花哨的事情,就像将所有局部变量放入字典一样。
Because it is actually "fancier"
因为它实际上是“发烧友”
what you want is:
你想要的是:
apple = 1
banana = 'f'
carrot = 3
fruitdict = {}
# I want to set the key equal to variable name, and value equal to variable value
# is there a more Pythonic way to get {'apple': 1, 'banana': 'f', 'carrot': 3}?
names= 'apple banana carrot'.split() # I'm just being lazy for this post
items = globals() # or locals()
for name in names:
fruitdict[name] = items[name]
Honestly, what you are doing is just copying items from one dictionary to another.
老实说,您所做的只是将项目从一本字典复制到另一本字典。
(Greg Hewgill practically gave the whole answer, I just made it complete)
(Greg Hewgill 几乎给出了完整的答案,我刚刚完成了)
...and like people suggested, you should probably be putting these in the dictionary in the first place, but I'll assume that for some reason you can't
...就像人们建议的那样,您可能应该首先将这些放在字典中,但我认为出于某种原因您不能
回答by user1734291
a = "something"
randround = {}
randround['A'] = "%s" % a
Worked.
工作了。
回答by Arnout
Based on the answer by mouad, here's a more pythonic way to select the variables based on a prefix:
根据 mouad 的回答,这里有一种更 Pythonic 的方式来根据前缀选择变量:
# All the vars that I want to get start with fruit_
fruit_apple = 1
fruit_carrot = 'f'
rotten = 666
prefix = 'fruit_'
sourcedict = locals()
fruitdict = { v[len(prefix):] : sourcedict[v]
for v in sourcedict
if v.startswith(prefix) }
# fruitdict = {'carrot': 'f', 'apple': 1}
You can even put that in a function with prefix and sourcedict as arguments.
你甚至可以把它放在一个带有前缀和 sourcedict 作为参数的函数中。
回答by Christian Vanderwall
Here it is in one line, without having to retype any of the variables or their values:
这是在一行中,无需重新键入任何变量或其值:
fruitdict.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'fruitdict'})

