user58653
user58653

Reputation: 55

Append to dictionary based on list values

I have a list that contains 8634 values that are either 0, 1, 2, 3 or 4. I want to create a dictionary that also has 8634 key-value pairs that are based on the value in the list. For example, while traversing through the list, if it finds a zero then the key-value pair should be 0:Zero and so fourth until it reaches the end of the list.

Here is my code:

for i in label_list:
 if i == 0:
   dict.update({i:"Zero"})
 elif i == 1:
   dict.update({i:"One"})
 elif i == 2:
   dict.update({i:"Two"})
 elif i == 3:
   dict.update({i:"Three"})
 else:
   dict.update({i:"Four"})

The current code only produces 5 Key-Value pairs. My intention is to create a dataframe out of the result.

Upvotes: 0

Views: 79

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114320

Dictionaries can hold exactly one instance of a key. That's sort of the whole point of them.

If, on the other hand, your goal is to map numbers from zero to 8634 to their English names, then I have good news for you. I wrote and maintain a library of utility routines called haggis, which has a routine haggis.numbers.english that maps integers to their English names:

from haggis.numbers import english

...

numbers = {i: english(i) for i in range(len(label_list))}

Upvotes: 1

Mark
Mark

Reputation: 92440

Since you are looking to make a dataframe, you can can use pandas map() with a dictionary that maps numbers to words. For example:

import pandas as pd

words = {
    0: 'zero',
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four'
}

l = [0, 2, 3, 1, 4, 0, 1, 2]

nums = pd.Series(l)
pd.DataFrame({'n': nums, 'words':nums.map(words)})

Which creates the dataframe:

    n   words
0   0   zero
1   2   two
2   3   three
3   1   one
4   4   four
5   0   zero
6   1   one
7   2   two

Upvotes: 2

Related Questions