MMMMMCK
MMMMMCK

Reputation: 337

Replacing An Element in a Python List Using Dictionary

I have two items: a list of country codes as 2-character strings, and a dictionary that maps each string to a value. I'd like to iterate through the list and change each element to its corresponding value. Trying the method below:

countryList = kData['country'].tolist()
for i in countryList:
    i = countryCodes[i]
    print(i)

print(countryList)

Results in the following output:

75
234
39
['FR', 'GB', 'CA']

When I want the output to be:

75
234
39
[75, 234, 39]

Even though I'm setting each of element in the list and verifying that it HAS been changed by printing it, when I print the list as a whole the changes haven't carried over. What could I be doing wrong?

Upvotes: 0

Views: 54

Answers (2)

Ballack
Ballack

Reputation: 966

for i in countryList:
    i = countryCodes[i]

should change to

for index, val in enumerate(countryList):
    countryList[index] = countryCodes[val]

Because when you iterate an list through for i in countryList, the i is another variable, when you assign i to new value, the content of contryList remains unchanged, you need to use contryList[index] = val to make list change

Upvotes: 2

Michael Butscher
Michael Butscher

Reputation: 10959

You are only changing what the variable i refers to.

Better you create a new list:

countryList = kData['country'].tolist()

newList = []

for i in countryList:
    newList.append(countryCodes[i])
    print(i)

countryList = newList

print(countryList)

This can be written shorter but I don't want to confuse you.

Upvotes: 3

Related Questions