如何在python中将dict转换为表达式

时间:2015-05-16 07:05:20

标签: python python-2.7

我在使用python

实现某些逻辑时遇到问题

例如

{"a":"b", "c":1}

当我打印“a”时,我需要获得“b”,当我打印“c”时,我需要获得1个

如下所示

>>> a
'b'
>>> c
1

如何解决此问题

2 个答案:

答案 0 :(得分:2)

这样的东西
>>> input_dict = {"a":"b", "c":1}
>>> for key, value in input_dict.items():
...     try:
...             exec( "{} = {}".format(key, value))
...     except:
...             exec( "{} = {}".format(key, "'" + str(value) + "'"))
... 

>>> a
'b'
>>> c
1
  • 更复杂的测试用例

    >>> input_dict = {"a":"b", "c":1 , "d" : {1,2,3}}
    >>> for key, value in input_dict.items():
    ...     try:
    ...             exec( "{} = {}".format(key, value))
    ...     except:
    ...             exec( "{} = {}".format(key, "'" + str(value) + "'"))
    ... 
    >>> d
    set([1, 2, 3])
    >>> a
    'b'
    >>> c
    1
    

答案 1 :(得分:1)

通常你不应该这样做,因为你会污染模块命名空间。

In [1]: a
NameError: name 'a' is not defined

In [2]: c
NameError: name 'c' is not defined

In [3]: d={"a":"b", "c":1}   
In [4]: globals().update((k, v) for k, v in d.items() )

In [5]: a
Out[5]: 'b'

In [6]: c
Out[6]: 1