Reputation: 759
The first Dict is fixed.This Dict will remain as it is List of Countries with there Short Names.
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'}
However This Tuple result has multiple Dict inside it.This is the format in which MySQLdb returns result:
result =({'count': 1L, 'country': 'Eritrea'}, {'count': 1L, 'country': 'Togo'}, {'count': 1L, 'country': 'Sierra Leone'}, {'count': 3L, 'country': 'Bahamas'}, {'count': 1L, 'country': 'Ghana'})
Now i want to compare these both results With COUNTRY Names and If 'Country' in Result is present in firstDict then put the value.else put the 0 The result desired is:
mainRes={'ER':1,'TG':1,'BS':3,'GH':0,'LU':0}
Upvotes: 1
Views: 386
Reputation: 880937
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}
In Python2.6 or older, where there is no dict comprehenions, you could do:
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())
Upvotes: 4
Reputation: 3696
You don't have to go thru array conversion. Just use for loops as:
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
Upvotes: 0
Reputation: 179717
You can try something like
mainRes = dict.fromkeys(firstDict.itervalues(), 0)
for row in result:
countryCode = firstDict.get(row['country'].upper())
if countryCode:
mainRes[countryCode] = row['count']
Upvotes: 0