有没有更简单的方法在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)
答案 0 :(得分:62)
for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
答案 1 :(得分:14)
globals()
函数返回包含所有全局变量的字典。
>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}
还有一个名为locals()
的类似函数。
我意识到这可能不是你想要的,但它可以提供一些深入了解Python如何提供对变量的访问。
编辑:听起来您的问题可以通过首先使用字典来解决:
fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
答案 2 :(得分:5)
单行是: -
fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))
答案 3 :(得分:2)
根据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}
你甚至可以把它放在一个带有prefix和sourcedict作为参数的函数中。
答案 4 :(得分:2)
这里有一行,无需重新输入任何变量或其值:
fruitdict.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'fruitdict'})
答案 5 :(得分:1)
如果你想绑定变量本身的位置,那就是:
>>> 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
答案 6 :(得分:1)
尝试:
to_dict = lambda **k: k
apple = 1
banana = 'f'
carrot = 3
to_dict(apple=apple, banana=banana, carrot=carrot)
#{'apple': 1, 'banana': 'f', 'carrot': 3}
答案 7 :(得分:0)
为什么你不这样做:
fruitdict = {
'apple':1,
'banana':'f',
'carrot':3,
}
locals().update(fruitdict)
更新:
不要使用上面的代码检查评论。
顺便说一下你为什么不标记你想要获得的变量我不知道 也许是这样的:
# 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])
答案 8 :(得分:0)
嗯,这有点,嗯......非Pythonic ......丑陋...... hackish ......
这是一段代码,假设您要创建一个包含所有局部变量的字典 在采取特定检查点后创建:
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]
请注意,我们明确地将“检查点”键添加到我们对locals().keys()
的捕获中我还明确地将其切片,尽管在这种情况下它不应该是必需的,因为引用必须被展平将其添加到['checkpoint']列表中。但是,如果您使用此代码的变体并尝试快捷方式['checkpoint'] + portion (because that key was already in
locals(), for example) ... then, without the [:] slice you could end up with a reference to the
locals()。keys()`,其值会随着您添加变量而改变。
Offhand我想不出一种方法可以调用类似new_vars.update()
之类的东西来添加/更新密钥列表。所以for
循环最便携。我想字典理解可以在更新的Python版本中使用。然而,woudl似乎只不过是一轮代码高尔夫球。
答案 9 :(得分:0)
这个问题实际上已得到解答,但我只想说你说的很有意思
这不是什么花哨的事,比如说 将所有局部变量放入 字典。
因为它实际上是“发烧友”
你想要的是:
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]
老实说,你所做的只是将项目从一个字典复制到另一个字典。
(Greg Hewgill几乎给出了完整的答案,我刚刚完成了)
......和人们建议的一样,你可能应该首先将这些放在字典中,但我会假设你出于某些原因不能
答案 10 :(得分:-1)
这不是最优雅的解决方案,只能在90%的时间内起作用:
def vardict(*args):
ns = inspect.stack()[1][0].f_locals
retval = {}
for a in args:
found = False
for k, v in ns.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one local variable: " + str(a))
found = True
if found:
continue
if 'self' in ns:
for k, v in ns['self'].__dict__.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one instance attribute: " + str(a))
found = True
if found:
continue
for k, v in globals().items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one global variable: " + str(a))
found = True
assert found, "Couldn't find one of the parameters."
return retval
如果将相同的引用存储在多个变量中,但是如果多个变量存储的是相同的小int,则会遇到问题。
答案 11 :(得分:-2)
a = "something"
randround = {}
randround['A'] = "%s" % a
的工作。