我对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"
我该怎么做呢?谢谢你的帮助!
如果您可以确定原始字典的内容,并且首先无法以所需的格式获取它,那么这是一个使用的想法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'