第一个Dict是固定的。这个Dict将保留为具有短名称的国家列表。
firstDict={'ERITREA': 'ER', 'LAOS': 'LA', 'PORTUGAL': 'PT', "D'IVOIRE": 'CI', 'MONTENEGRO': 'ME', 'NEW CALEDONIA': 'NC', 'SVALBARD AND JAN MAYEN': 'SJ', 'BAHAMAS': 'BS', 'TOGO': 'TG', 'CROATIA': 'HR', 'LUXEMBOURG': 'LU', 'GHANA': 'GH'}
但是这个元组结果里面有多个Dict。这是MySQLdb返回结果的格式:
result =({'count': 1L, 'country': 'Eritrea'}, {'count': 1L, 'country': 'Togo'}, {'count': 1L, 'country': 'Sierra Leone'}, {'count': 3L, 'country': 'Bahamas'}, {'count': 1L, 'country': 'Ghana'})
现在我想将这两个结果与COUNTRY名称进行比较,如果在FirstDict中出现了Result中的'Country',则将value.else放入0 所需的结果是:
mainRes={'ER':1,'TG':1,'BS':3,'GH':0,'LU':0}
答案 0 :(得分:4)
In [2]: firstDict={'ERITREA': 'ER', 'LAOS': 'LA', 'PORTUGAL': 'PT', "D'IVOIRE": 'CI', 'MONTENEGRO': 'ME', 'NEW CALEDONIA': 'NC', 'SVALBARD AND JAN MAYEN': 'SJ', 'BAHAMAS': 'BS', 'TOGO': 'TG', 'CROATIA': 'HR', 'LUXEMBOURG': 'LU', 'GHANA': 'GH'}
In [3]: result =({'count': 1L, 'country': 'Eritrea'}, {'count': 1L, 'country': 'Togo'}, {'count': 1L, 'country': 'Sierra Leone'}, {'count': 3L, 'country': 'Bahamas'}, {'count': 1L, 'country': 'Ghana'})
In [4]: resdict = {r['country'].upper():r['count'] for r in result}
In [5]: mainRes = {abbrev:resdict.get(country,0) for country, abbrev in firstDict.items()}
In [6]: mainRes
Out[6]:
{'BS': 3L,
'CI': 0,
'ER': 1L,
'GH': 1L,
'HR': 0,
'LA': 0,
'LU': 0,
'ME': 0,
'NC': 0,
'PT': 0,
'SJ': 0,
'TG': 1L}
在没有dict comprehenions的Python2.6或更早版本中,你可以这样做:
In [13]: resdict = dict((r['country'].upper(), r['count']) for r in result)
In [14]: mainRes = dict( (abbrev, resdict.get(country,0)) for country, abbrev in firstDict.items())
答案 1 :(得分:0)
您可以尝试类似
的内容mainRes = dict.fromkeys(firstDict.itervalues(), 0)
for row in result:
countryCode = firstDict.get(row['country'].upper())
if countryCode:
mainRes[countryCode] = row['count']
答案 2 :(得分:0)
您不必通过数组转换。只需使用for循环:
import string
desired_result = {}
for c in result:
country = string.upper(c['country'])
if country in firstDict:
desired_result[firstDict[country]] = c['count']
print desired_result