把字典分成变量

2024-05-14 19:56:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,目前正在通过字典进行更多的学习。

我在想

如果我有一个像:d = {'key_1': 'value_a', 'key_2': 'value_b'}这样的字典,我想把这个字典分成变量,其中每个变量都是字典中的键,每个变量的值都是字典中键的值。

什么才是达到这个目的的最好方法?

d = {'key_1': 'value_a', 'key_2': 'value_b'}
#perform the command and get
key_1 = 'value_a'
key_2 = 'value_b'

我试过:key_1, key_2 = d但没用。

基本上,我是在寻求专家的智慧来找出是否有更好的方法来将两行代码缩减为一行。

注意:这不是动态变量创建。


Tags: andthe方法key代码目的get字典
3条回答

问题是dict是无序的,所以不能使用简单的d.values()解包。当然,您可以先按键对dict进行排序,然后解压这些值:

# Note: in python 3, items() functions as iteritems() did
#       in older versions of Python; use it instead
ds = sorted(d.iteritems())
name0, name1, name2..., namen = [v[1] for v in ds]

你也可以,至少在一个物体内,做如下事情:

for k, v in dict.iteritems():
    setattr(self, k, v)

此外,正如我在上面的注释中所提到的,如果您可以将需要解压字典作为变量的所有逻辑作为函数获取,那么您可以执行以下操作:

def func(**kwargs):
    # Do stuff with labeled args

func(**d)

以前没有提到过的解决方案是

dictget = lambda d, *k: [d[i] for i in k]

然后使用它:

key_1, key_2 = dictget(d, 'key_1', 'key_2')

它的优点是,即使需要检索更多的变量,它也是非常可读的。

然而,更具可读性的是“真实的”函数,如

def dictget(d, *k):
    """Get the values corresponding to the given keys in the provided dict."""
    return [d[i] for i in k]
    # or maybe
    return (d[i] for i in k) # if we suppose that we have bigger sets of result
    # or, equivalent to this
    for i in k:
        yield d[i]

它还支持使用docstring进行注释,并且是首选。

现有的答案可以工作,但它们实际上都在重新实现一个已经存在于Python标准库中的函数:^{}

docs

Return a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example:

After f = itemgetter(2), the call f(r) returns r[2].

After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]).


换言之,您的解构dict赋值变得类似于:

from operator import itemgetter

d = {'key_1': 'value_a', 'key_2': 'value_b'}
key_1, key_2 = itemgetter('key_1', 'key_2')(d)

# prints "Key 1: value_a, Key 2: value_b"
print("Key 1: {}, Key 2: {}".format(key_1, key_2))

相关问题 更多 >

    热门问题