基于变量名称解压缩

时间:2016-04-18 20:00:02

标签: python python-2.7 python-3.x

我想解压缩像:

one, two, three, four = unpack(this_dict)

其中

this_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

我唯一的问题是unpack需要知道它将分配给哪些名称。你是如何在python中做到这一点的?谢谢

2 个答案:

答案 0 :(得分:5)

Dicts是无序的,所以如果你想以某种顺序解包你需要使用这些键,你可以创建一个函数来传递你想要访问的任何键:

from operator import itemgetter
def unpack(d, *args):
    return itemgetter(*args)(d)
one, two, three, four = unpack(this_dict, "one" ,"two" ,"three" ,"four")

print(one, two, three, four)

或使用地图:

def unpack(d, *args):
    return map(d.get, args) 
one, two, three, four = unpack(this_dict, "one" ,"two" ,"three" ,"four")

print(one, two, three, four)

如果你传递了一个不存在的密钥,那么第一个会给你一个KeyError,后者会将任何缺失密钥的变量设置为None,这是值得记住的。

答案 1 :(得分:3)

你绝对不应该这样做。但是,如果您在模块级范围内,则可以将字典添加到globals()

this_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
globals().update(this_dict)

print one, two, three, four
# 1 2 3 4

请注意,如果您的字典包含listintFalse等字符,则此方法很危险。您可以在技术上执行此操作一个函数或类,但情况会更糟。