将字典条目转换为变量-python [英] convert dictionary entries into variables - python

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

问题描述

是否存在一种将字典的值分配给其键的pythonic方法,以便将字典条目转换为变量? 我尝试了这个:

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:

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

        exec(key)=val
                 ^ 
        SyntaxError: invalid syntax

更新:也许我应该更具体一些:实际上,我可以肯定键值对是正确的,因为以前我曾将它们定义为变量.然后,我将这些变量存储在字典中(作为键值对),并希望在其他函数中重用它们.我可以在新函数中重新定义它们,但是由于我可能有一个包含约20个条目的字典,所以我认为可能会有一种更有效的方法.

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.

推荐答案

这就是我想要的:

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

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

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