将字典划分为变量 [英] Divide a dictionary into variables

查看:50
本文介绍了将字典划分为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am studying Python and currently going through some more learning with dictionaries.

我在想;

如果我有一个像这样的字典:d = {'key_1': 'value_a', 'key_2': 'value_b'} 并且我想将此字典分开/划分为变量,其中每个变量是字典中的一个键,每个变量值都是字典中该键的值.

If I have a dictionary like: d = {'key_1': 'value_a', 'key_2': 'value_b'} and I want separate/divide this dictionary into variables where each variable is a key from the dictionary and each variables value is the value of that key in the dictionary.

实现这一目标的最佳 Pythonic 方法是什么?

What would be the best pythonic way to achieve this?

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 但没有用.

基本上我正在寻求专家的智慧,以找出是否有更好的方法将 2 行代码缩减为 1 行.

Basically I am seeking expert's wisdom to find out if there is a better way to reduce 2 lines of code into one.

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

Note: This is not a dynamic variable creation.

推荐答案

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

Problem is that dicts are unordered, so you can't use simple unpacking of d.values(). You could of course first sort the dict by key, then unpack the values:

# 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]

您也可以,至少在一个对象中,执行以下操作:

You could also, at least within an object, do something like:

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

此外,正如我在上面的评论中提到的,如果您可以将需要解压字典的所有逻辑作为函数的变量,您可以这样做:

Additionally, as I mentioned in the comment above, if you can get all your logic that needs your unpacked dictionary as variables in to a function, you could do:

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

func(**d)

这篇关于将字典划分为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆