将字典条目转换为变量 - python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18090672/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:54:19  来源:igfitidea点击:

convert dictionary entries into variables - python

pythondictionary

提问by HappyPy

Is there a pythonic way to assign the values of a dictionary to its keys, in order to convert the dictionary entries into variables? I tried this out:

是否有一种 Pythonic 方法可以将字典的值分配给它的键,以便将字典条目转换为变量?我试过了:

>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
        exec('exec(key)=val')

        exec(key)=val
                 ^ 
        SyntaxError: invalid syntax

UPDATE: Perhaps I should have been more specific: I am actually certain that the key-value pairs are correct because they were previously defined as variables by me before. I then stored these variables in a dictionary (as key-value pairs) and would like to reuse them in a different function. I could just define them all over again in the new function, but because I may have a dictionary with about 20 entries, I thought there may be a more efficient way of doing this.

更新:也许我应该更具体:我实际上确定键值对是正确的,因为它们之前被我定义为变量。然后我将这些变量存储在字典中(作为键值对),并希望在不同的函数中重用它们。我可以在新函数中重新定义它们,但是因为我可能有一个包含大约 20 个条目的字典,我认为可能有一种更有效的方法来做到这一点。

采纳答案by HappyPy

This was what I was looking for:

这就是我要找的:

>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
        exec(key + '=val')

回答by user2357112 supports Monica

You already have a perfectly good dictionary. Just use that. If you know what the keys are going to be, and you're absolutely sure this is a reasonable idea, you can do something like

你已经有一本非常好的字典了。就用那个。如果您知道密钥将是什么,并且您绝对确定这是一个合理的想法,您可以执行以下操作

a, b = d['a'], d['b']

but most of the time, you should just use the dictionary. (If using the dictionary is awkward, you are probably not organizing your data well; ask for help reorganizing it.)

但大多数时候,你应该只使用字典。(如果使用字典很尴尬,你可能没有很好地组织你的数据;寻求帮助重新组织它。)

回答by tdelaney

Consider the "Bunch" solution in Python: load variables in a dict into namespace. Your variables end up as part of a new object, not locals, but you can treat them as variables instead of dict entries.

考虑Python 中的“Bunch”解决方案:将 dict 中的变量加载到 namespace。您的变量最终会成为新对象的一部分,而不是本地对象,但您可以将它们视为变量而不是 dict 条目。

class Bunch(object):
    def __init__(self, adict):
        self.__dict__.update(adict)

d = {'a':1, 'b':2}
vars = Bunch(d)
print vars.a, vars.b

回答by restrepo

Use pandas:

使用熊猫:

import pandas as pd
var=pd.Series({'a':1, 'b':2})
#update both keys and variables
var.a=3
print(var.a,var['a'])

回答by Peque

You can do it in a single line with:

您可以在一行中使用:

>>> d = {'a': 1, 'b': 2}
>>> locals().update(d)
>>> a
1

However, you should be careful with how Python may optimize locals/globals access when using this trick.

但是,在使用此技巧时,您应该注意Python 如何优化本地/全局访问

Note

笔记

I think editing locals()like that is generally a bad idea. If you think globals()is a better alternative, think it twice! :-D

我认为这样的编辑locals()通常是一个坏主意。如果您认为globals()是更好的选择,请三思!:-D

Instead, I would rather always use a namespace.

相反,我宁愿始终使用命名空间。

With Python 3 you can:

使用 Python 3,您可以:

>>> from types import SimpleNamespace    
>>> d = {'a': 1, 'b': 2}
>>> n = SimpleNamespace(**d)
>>> n.a
1

If you are stuck with Python 2 or if you need to use some features missing in types.SimpleNamespace, you can also:

如果您坚持使用 Python 2 或者如果您需要使用 中缺少的某些功能types.SimpleNamespace,您还可以:

>>> from argparse import Namespace    
>>> d = {'a': 1, 'b': 2}
>>> n = Namespace(**d)
>>> n.a
1

If you are not expecting to modify your data, you may as well consider using collections.namedtuple, also available in Python 3.

如果您不希望修改您的数据,您不妨考虑使用collections.namedtuple,也可在 Python 3 中使用。

回答by suhailvs

you can use operator.itemgetter

你可以使用operator.itemgetter

>>> from operator import itemgetter
>>> d = {'a':1, 'b':2}
>>> a, b = itemgetter('a', 'b')(d)
>>> a
1
>>> b
2