Reputation: 861
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?
Upvotes: 3
Views: 31683
Reputation: 21
characters = ['Sonic',
'Knuckles',
'Tails',
'Amy',
'Cream',
'Shadow',
'Rouge',
'Silver',
'Blaze']
slice = {}
for character in characters:
slice[character]=len(character)
print(slice)
# TH OUTPUT WILL BE THIS :
# {'Sonic': 5, 'Knuckles': 8, 'Tails': 5, 'Amy': 3, 'Cream': 5, 'Shadow': 6, 'Rouge': 5, 'Silver': 6, 'Blaze': 5}
# IF YOU WANT TOI GET THE USER INPUT CHARACTERS JUST USE OTHER
#LOOPS TO HOW MUCH YOU WANT TO GIVE
# THE SOLUTION OF ABOVE QUESTION IS THIS
Upvotes: 0
Reputation: 164623
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}
Upvotes: 1
Reputation: 1051
Update your code to :
>>> slice = dict()
>>> for character in characters:
... slice.update({character:len(character)})
...
Upvotes: 7
Reputation: 294
You should define slice
as an empty dictionary outside of your loop. As it currently stands, you redefine the dictionary for each character as you iterate.
Upvotes: 0