Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to dictionary with loop

I want to create a dictionary with a predetermined list, however, I can't seem to figure it out how to avoid overwriting instead of appending, and I'm not sure if I can avoid importing any other modules.

The scope is that I have a data frame of 1 column of character names with ID numbers attached to the names from reading an excel file in, sega_df:

          Character
0         Amy (335)
1       Tails (359)
2      Shadow (357)
3      Shadow (357)
4       Blaze (337)

Then I have a list of all the characters, characters, without their ID numbers:

['Sonic', 'Knuckles', 'Tails', 'Amy', 'Cream', 'Shadow', 'Rouge', 'Silver', 'Blaze']

I want to create a dictionary so I can replace sega_df.Character's by slicing each row entry with the len() of the characters in characters, producing desired_sega_df:

         Character
    0          Amy
    1        Tails
    2       Shadow
    3       Shadow
    4        Blaze

The dictionary I want to create will have keys of the characters names without their ID numbers, and values of the len() of their names. The dictionary is slice:

{'Sonic': 5, 
 'Knuckles': 8, 
 'Tails': 5, 
 'Amy': 3, 
 'Cream': 5, 
 'Shadow': 6, 
 'Rouge': 5, 
 'Silver': 6, 
 'Blaze': 5}

Even when I use .update() it still repeatedly overwrites with only Blaze as the key and 5 as the value.

>>> for character in characters:
...     slice = {character: len(character)}
...     slice.update({character:len(character)})
...
>>> slice
{'Blaze': 5}

My question is: How can I modify my loop to add key-value pairs of all the characters to slice rather than continuously overwriting them?

like image 344
florence-y Avatar asked Dec 19 '25 12:12

florence-y


2 Answers

Update your code to :

>>> slice = dict()
>>> for character in characters:
...     slice.update({character:len(character)})
...
like image 159
Venkata Gogu Avatar answered Dec 22 '25 03:12

Venkata Gogu


Here's the Pandorable solution. For splitting Character, you have a choice of splitting on whitespace or slicing on character count. Which works best depends on your dataset.

Whether you choose the pure Python or Pandas solution, you do not need to use an explicit loop.

# remove last 6 characters to leave names
df['Character'] = df['Character'].str[:-6]  # or, df['Chracter'].str.split().str[0]

# calculate length in new series
df['Length'] = df['Character'].map(len)

# convert to dictionary
d = df.set_index('Character')['Length'].to_dict()

print(d)

{'Amy': 3, 'Tails': 5, 'Shadow': 6, 'Blaze': 5}
like image 45
jpp Avatar answered Dec 22 '25 01:12

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!