Making a dictionary of from a list and a dictionary

Viewed 75

I am trying to create a dictionary of codes that I can use for queries and selections. Let's say I have a dictionary of state names and corresponding FIPS codes:

 statedict ={'Alabama': '01', 'Alaska':'02', 'Arizona': '04',... 'Wyoming': '56'}

And then I have a list of FIPS codes that I have pulled in from a Map Server request:

fipslist = ['02121', '01034', '56139', '04187', '02003', '04023', '02118']

I want to sort of combine the key from the dictionary (based on the first 2 characters of the value of that key) with the list items (also, based on the first 2 characters of the value of that key. Ex. all codes beginning with 01 = 'Alabama', etc...). My end goal is something like this:

fipsdict ={'Alabama': ['01034'], 'Alaska':['02121', '02003','02118'], 'Arizona': ['04187', '04023'],... 'Wyoming': ['56139']}

I would try to set it up similar to this, but it's not working quite correctly. Any suggestions?

fipsdict = {}
tempList = []
for items in fipslist:
    for k, v in statedict:
        if item[:2] == v in statedict:
        fipsdict[k] = statedict[v]
        fipsdict[v] = tempList.extend(item)
3 Answers

A one liner with nested comprehensions:

>>> {k:[n for n in fipslist if n[:2]==v] for k,v in statedict.items()}
{'Alabama': ['01034'],
 'Alaska': ['02121', '02003', '02118'],
 'Arizona': ['04187', '04023'],
 'Wyoming': ['56139']}

You will have to create a new list to hold matching fips codes for each state. Below is the code that should work for your case.

 for state,two_digit_fips in statedict.items():
     matching_fips = []
     for fips in fipslist:
             if fips[:2] == two_digit_fips:
                     matching_fips.append(fips)
     state_to_matching_fips_map[state] = matching_fips

>>> print(state_to_matching_fips_map)
{'Alabama': ['01034'], 'Arizona': ['04187', '04023'], 'Alaska': ['02121', '02003', '02118'], 'Wyoming': ['56139']}

For both proposed solutions I need a reversed state dictionary (I assume that each state has exactly one 2-digit code):

reverse_state_dict = {v: k for k,v in statedict.items()}

An approach based on defaultdict:

from collections import defaultdict
fipsdict = defaultdict(list)    

for f in fipslist:
    fipsdict[reverse_state_dict[f[:2]]].append(f)

An approach based on groupby and dictionary comprehension:

from itertools import groupby

{reverse_state_dict[k]: list(v) for k,v 
            in (groupby(sorted(fipslist), key=lambda x:x[:2]))}
Related