英文:
Create Dictionary with name and value of list of variables
问题
我有一个Python中的变量列表,我想要创建一个字典,其中键将是变量的名称,值将是变量的内容。
a, b, c = 1, 2, 3
my_list = [a, b, c]
my_dict = {f'{item=}'.split('=')[0]: item for item in my_list}
如果我运行上面的代码,我会得到以下结果:
{'item': 3}
但我想要得到以下结果:
```python
{'a': 1, 'b': 2, 'c': 3}
提前感谢。
英文:
I have a list of variables in python. And I want to create a dictionary whose key will be the name of the variable and the value will be the content.
a,b,c = 1,2,3
list = [a,b,c]
dic = {f'{item=}'.split('=')[0]:item for item in list}
If I run the previous code, I get as result the following:
{'item': 3}
And i would like to get the following:
{'a':1,'b':2,'c':3}
Thanks in advance
答案1
得分: 1
以下是翻译好的部分:
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
d = {f'{namestr(i, globals())[0]}': i for i in list}
这段代码的作用是创建一个字典,将变量名和其对应的值关联起来,得到的结果如下:
{'a': 1, 'b': 2, 'c': 3}
这种方法可能并不是一个好主意,特别是在你的示例中。例如,在Python中,整数是相同的“对象” - 如果我这样写:
a = 1
e = 1
a is e
会得到 True
,即使我在测试身份而不是相等性。所以,一旦我有另一个具有与你的示例中相同值的变量,is
测试可能会评估为 True,从而导致错误的结果。举个例子:
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
__ = 1
d = {f'{namestr(i, globals())[0]}': i for i in list}
结果是:
{'__': 1, 'b': 2, 'c': 3}
这只是一种解释,说明你可以这样做,而不是你应该以这种方式做。但如果你有一个非常简短的笔记本或其他东西,你知道不会有其他变量重叠,你可能可以这样处理。
英文:
One potential way of doing it is like so (see https://stackoverflow.com/a/592891/11530613):
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
d = {f'{namestr(i, globals())[0]}': i for i in list}
This gives:
{'a': 1, 'b': 2, 'c': 3}
This is definitely a bad idea though, especially with your toy example. For example, integers in Python are the same "object"—if I say:
a = 1
e = 1
a is e
I get True
, even though I'm testing identity and not equality. So the moment I have another variable with the same value from your toy example above, the is
test might evaluate to True, and you could get bad results. Case in point:
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
__ = 1
d = {f'{namestr(i, globals())[0]}': i for i in list}
yields
{'__': 1, 'b': 2, 'c': 3}
This is simply an explanation of how you could do it, not that you ever should do it this way. But if you had like, a very short notebook or something and you knew no other variables would ever overlap, you might hack it this way.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论