AppCreator
AppCreator

Reputation: 241

How to replace list items with the corresponding value from a dictionary in this example? Using python

I have this list:

['79.9', '79.9', '79.9', '79.9', '103.2', '103.2']

I want to replace the list items with the corresponding value from this dictionary:

ValueDict = {
    "243": "0",
    "219.70000000000002": "1",
    "196.4": "2",
    "173.1": "3",
    "149.79999999999998": "4",
    "126.5": "5",
    "103.2": "6",
    "79.9": "7",
    "56.59999999999999": "8",
    "33.3": "9",
    "10": "10",
}

So the result will be a list like this: [7, 7, 7, 7, 6, 6]

How can I do this?

Upvotes: 0

Views: 60

Answers (6)

balderman
balderman

Reputation: 23815

something like the below

lst = ['79.9', '79.9', '79.9', '79.9', '103.2', '103.2']
ValueDict = {
    "243": "0",
    "219.70000000000002": "1",
    "196.4": "2",
    "173.1": "3",
    "149.79999999999998": "4",
    "126.5": "5",
    "103.2": "6",
    "79.9": "7",
    "56.59999999999999": "8",
    "33.3": "9",
    "10": "10",
}
new_lst = [ValueDict.get(x,'-1') for x in lst]
print(new_lst)

Upvotes: 0

Alis
Alis

Reputation: 80

This should work:

[int(ValueDict[x]) for x in list1] 

[7, 7, 7, 7, 6, 6]

:)

Upvotes: 0

Aleksei Khatkevich
Aleksei Khatkevich

Reputation: 2197

a = ['79.9', '79.9', '79.9', '79.9', '103.2', '103.2']
b = {
    "243": "0",
    "219.70000000000002": "1",
    "196.4": "2",
    "173.1": "3",
    "149.79999999999998": "4",
    "126.5": "5",
    "103.2": "6",
    "79.9": "7",
    "56.59999999999999": "8",
    "33.3": "9",
    "10": "10",
}
c = [b.get(i, i)for i in a]
c
['7', '7', '7', '7', '6', '6']

Upvotes: 0

Bartosz Karwacki
Bartosz Karwacki

Reputation: 331

final_list = [ValueDict[i] for i in your_list if i in ValueDict]

Upvotes: 2

Val Berthe
Val Berthe

Reputation: 2054

You could do it with list comprehension.

final_list = [ValueDict[value] for value in my_list] 

Upvotes: 0

user15801675
user15801675

Reputation:

Use enumerate for adding a counter to the list, then check if the element is in dictionary, and call the value

for i,j in enumerate(l):
    if j in ValueDict:
        l[i]=ValueDict[j]
print(l)

Output:

['7', '7', '7', '7', '6', '6']

Upvotes: 0

Related Questions