我有一本这样的字典:
test = {'tuple':(1, 2, 3, 4), 'string':'foo', 'integer':5}为了减少浪费的空间,我想将这些值解压缩到单独的变量中。我知道解开字典的关键字是可能的:
>>> a, b, c = test
>>> print(a, b, c)
tuple string integer但我想做的是解开字典中的值。像这样的东西:
>>> tuple, string, integer = test
>>> print(tuple, string, integer)
(1, 2, 3, 4) string 5这个是可能的吗?如果没有,我认为如果您解压的变量与字典中的值相对应,它应该将值解压到适当的变量中(如上图所示)。
或者我唯一的方法就是这样做?
>>> tuple, string, integer = test['tuple'], test['string'], test['integer']发布于 2017-04-26 02:10:03
假设您使用的是早于3.6的python版本,只需按键对值进行排序,然后按字母顺序解包……
integer, string, tup = [i[1] for i in sorted(test.items(), key=lambda x: x[0])]然后,即使您添加了更多的键,您也只需要记住字母顺序,尽管我看不出仅使用dict这种方法有多实用
发布于 2017-04-26 01:59:24
假设dict上的键数是静态的,您可以首先使用values()检索它,然后将其分配给var:
>>> tuple, string, integer = test.values()
>>> print(tuple, string, integer)
(1, 2, 3, 4) foo 5有关更多信息,请访问https://docs.python.org/3.6/library/stdtypes.html#dict
编辑:正如评论中所说,python不保证键的顺序,因此,更好的解决方案是:
>>> for key in test:
globals()[key] = test[key]
>>> print(tuple, string, integer)
(1, 2, 3, 4) foo 5此外,这也解决了可变dict长度的问题。
发布于 2017-04-26 02:06:58
如果顺序不是问题,您可以使用以下命令:
test = {'tuple':(1, 2, 3, 4), 'string':'foo', 'integer':5}
print([test[x] for x in test.keys()])请注意,如果您希望列表的格式与之前显示的格式相同,则会输出一个列表:
test = {'tuple':(1, 2, 3, 4), 'string':'foo', 'integer':5}
print(' '.join([str(test[x]) for x in test.keys()]))当然,如果顺序很重要,您可以从test.keys()中创建一个排序列表并对其进行迭代,例如使用sorted(test.keys())。
祝好运!
编辑:
inty, stringy, tuply = [test[x] for x in sorted(test.keys())]将在本例中产生所需的结果,但请注意,添加更多键可能会改变顺序!
https://stackoverflow.com/questions/43617791
复制相似问题