0

Let's say I have a dictionary of all states abbreviations as a key, and the long names as the value:

statesDict = {'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas',...}

I also have a list of pre-selected state abbreviations:

statesAbbrv = ['AL', 'CA', 'CO', 'DE']

Based on the items in the cleanStates list, I want to chose only the values (the long names) for the state abbreviations keys in the stateNames dictionary and place them in a new list; stateNames = [] So, the results of the comparison will look like this:

stateNames = ['Alabama', 'California', 'Colorado', 'Deleware']

I was thinking the following, but it's not working. What am I doing wrong here?

stateNames = []
for i in statesAbbrv:
    for k, v in statesDict:
        if stateDict[k] == stateAbbrv[i]:
            stateNames.append(stateDict(k))
print stateNames
gwydion93
  • 1,681
  • 3
  • 28
  • 59

7 Answers7

4

Functionally1, you can use map2 with dict.get:

stateNames = list(map(statesDict.get, statesAbbrv))

If no match is found for an abbreviation, this will give None. A stricter version which will yield KeyError:

stateNames = list(map(statesDict.__getitem__, statesAbbrv))

The latter is akin to the list comprehension, as [] is syntax to access __getitem__:

stateNames = [statesDict[i] for i in statesAbbrv]

If you wish to supply a fallback if a key is not found, use a list comprehension with dict.get:

stateNames = [statesDict.get(i, 'Fallback State') for i in statesAbbrv]

1 Functional programming is a style of programming that treats computation as the evaluation of mathematical functions. See also Functional programming vs Object Oriented programming.

2 In Python 2.x, explicit list conversion is not necessary since map returns a list. In Python 3, map returns an iterable, which will need to be exhausted via list.

jpp
  • 159,742
  • 34
  • 281
  • 339
3

This is a typical job for a list comprehension:

stateNames = [statesDict.get(state, state) for state in statesAbbrv]
print(stateNames)
#['Alabama', 'CA', 'CO', 'DE']

Note that if a state abbreviation for some reason is not in the dictionary, it will be used as the state name itself.

DYZ
  • 55,249
  • 10
  • 64
  • 93
2
stateNames = [stateDict[k] for k in statesAbbrv if k in stateDict]

using list comprehensions.

modesitt
  • 7,052
  • 2
  • 34
  • 64
  • This was the easiest and most direct solution. I will review list comprehension so that it is more obvious. Thanks to all. – gwydion93 Aug 01 '18 at 19:59
2

Iterate through the list statesAbbrv and lookup the values in statesDict

statesNames = [statesDict[n] for n in statesAbbrv]
W Stokvis
  • 1,409
  • 8
  • 15
0
stateNames = []
for i statesAbbrv:
    for k, v in statesDict.iteritems():
        if stateDict[k] == stateAbbrv[i]:
            stateNames.append(stateDict(k))
print stateNames

You need to add iteritems() to make the dictionary iterable on python 2.7.

ltd9938
  • 1,444
  • 1
  • 15
  • 29
0

Serious typo errors in your question. Well, here is the answer (Just after removing errors in your own code):

statesDict = {'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas'}
statesAbbrv = ['AL', 'AK']

stateNames = []
for i in statesAbbrv:
    for k in statesDict.keys():
        if k == i:
            stateNames.append(statesDict[k])
print (stateNames)
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • 2
    this solution most closely aligns with the original code - but is terribly inefficient and verbose for a problem that should be solved directly. – modesitt Aug 01 '18 at 19:12
  • Well before you comment or downvote, read CAREFULLY what the OP asked. He/She said "What am I doing wrong here?". So before you go downvoting, make sure you understand what OP wants. My answer was to tell him/her what he is doing wrong. Clearly, OP seems to be a beginner. So it's better to teach him/her what's goin wrong in his/her solution. – Sheldore Aug 01 '18 at 19:15
  • i completely agree, but along with that one should include the **right** way to do things - point taken tho – modesitt Aug 01 '18 at 19:16
  • If everyone starts posting new "not so straightforward" solutions, how will a beginner learn and get to know what were the sources of error. I thought of doing something different rather than posting complicated (yet more efficient) solutions. If point is taken, I would ask to revert your vote in the spirit of my defense – Sheldore Aug 01 '18 at 19:17
  • the list comprehension is quite *readable* if that is the argument. i would call this *complicated*. Also SO does not allow it to be removed – modesitt Aug 01 '18 at 19:19
  • That's not the argument. My argument was that I tried to answer what the OP was having errors with. Clearly, I don't want to have any more argument with you. Your downvote is fine with me. Period. – Sheldore Aug 01 '18 at 19:21
0
stateNames = [statesDict.get(i) for i in statesAbbrv]
Jouhar N
  • 311
  • 1
  • 4