从旧词典键

时间:2015-12-18 18:19:09

标签: python dictionary

我对Python很陌生,并且很难从动态创建的字典创建局部变量(例如,对于我正在运行的进程的每次迭代,字典可能包含不同数量的地址项。)

我有以下字典:

{"item['address1']": u"1 High Street", "item['address2']": u'FY3 9JH Blackpool', "item['address3']": u'United Kingdom'}

想获得如下字典:

item['address1'] = "1 High Street"
item['address2'] = "FY3 9JH Blackpool"
item['address3'] = "United Kingdom"

我该怎么做呢?非常感谢你的帮助!

2 个答案:

答案 0 :(得分:5)

如果您可以确定原始词典的内容并且无法首先以所需的格式获取,那么使用re就可以了。

>>> import re
>>> old = {"item['address1']": u"1 High Street", "item['address2']": u'FY3 9JH Blackpool', "item['address3']": u'United Kingdom'}
>>> item = {re.sub("^item\['(.*)'\]$", r'\1', k) : old[k] for k in old}
>>> item
{'address1': u'1 High Street', 'address2': u'FY3 9JH Blackpool', 'address3': u'United Kingdom'}
>>> item['address1']
u'1 High Street'

答案 1 :(得分:0)

您不需要正则表达式,您有多种选择:

一旦您信任数据,您可以非常安全地exec

d = {"item['address1']": u"1 High Street", "item['address2']": u'FY3 9JH Blackpool',
     "item['address3']": u'United Kingdom'}
item = {}
for k, v in d.items():
    exec('{} = v'.format(k, v))

print(item)

输出:

{'address3': 'United Kingdom', 'address2': 'FY3 9JH Blackpool', 'address1': '1 High Street'}

str.index

d = {k[k.index("'")+1:k.rindex("'")]: v for k, v in d.items()}
print(d)

输出:

{'address1': '1 High Street', 'address2': 'FY3 9JH Blackpool', 'address3': 'United Kingdom'}

或只是str.strip

d = {k.strip("item[]")[1:-1]: v for k, v in d.items()}
print(d)

输出:

{'address2': 'FY3 9JH Blackpool', 'address3': 'United Kingdom', 'address1': '1 High Street'}