简体   繁体   中英

Python dictionary list retrieval process

I have been working to solve an issue involving a zip code to a territory based on a start range and end range within each territory. I can't seem to figure out how to use the dictionary below to run through my list of zip codes. Ultimately I need a list that says zip code 6015 belongs to territory A

mydict = {'Territory a': [60000,60999], 'Territory b': [90000,90999], 'Territory c': [70000,700999]}
myzips = [60015,60016,60017,90001,90002,90003,76550,76556,76557]

I've have research how to call values in a dictionary, but I don't see there is a good way to call the key, which in my case is the territory description. I'm not totally convinced that a dictionary is the way to go, but I can't think of another way all the elements stay together to be called on in a future function or loop.

Any help would be greatly appreciated.

Dictionaries are not meant to be used that way. Nonetheless, here is a solution that solves your issue.

mydict={'Territory a':[60000,60999],'Territory b': [90000,90999],'Territory c': [70000,70099]}
myzips =[60015,60016,60017,90001,90002,90003,76550,76556,76557]

for zipCode in myzips:
    for territory, postCodes in mydict.items():
        if (postCodes[0] <= zipCode <= postCodes[1]):
            print(str(zipCode) + " is in " + territory)
            break

For each zip given, we check if it is within the postal code range for all territories. If it is, we print it.

I would change mydict so the key is a zipcode and the value is the territory. Presumably there are no zip codes that belong to two territories.

newdict = {}
for territory, zipcodes in mydict.items():
    for zipcode in zipcodes:
        newdict[zipcode] = territory

Now you can get the territory for all the zipcodes in your list

for zipcode in myzips:
    print(zipcode, newdict.get(zipcode)

Note that in the data you posted, none of the zip codes in myzips are in mydict , so newdict.get will return None .

I got it to work with the help of Sri and Eric. I got it to work. I just made a distinct list for Territory(final_list) then loop through each one.

h = 0
while h < len(final_list) :

        for zipCode in myzips:
            for territory, postCodes in dict.items():
                if (postCodes[0] <= zipCode <= postCodes[1])and postCodes[2] == final_list[h] :
                    mylist2.append(str(zipCode)+","+territory)
                #break
        h += 1  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM