Reputation: 5
I have a .txt file that I opened and converted to a list using the .readlines method.
with open('superheroes.txt') as f:
hero = f.readlines()
I read it into an empty dictionary and since the file had a lot of duplicate strings but unique numbers, I chose to make the unique integers the keys and the duplicate strings the values using this code:
heroes = {}
for i in range(len(hero)):
name, num = hero[i].strip().split("\t")
heroes[int(num)] = name
The output of the print statement gives something similar to this:
{1867: 'Superman', 2904: 'Batman', 783: 'Wonderwoman', 4637: 'Superman', 8392: 'Batman', etc}
So far, I was able to append all the keys of a certain value into a unique list and manually sorted them using a for loop and an if statement:
superheroes = list(set(heroes.values())) #Gets all the unique values into one list
print(superheroes.sort()) #Ensures that the positions don't change when sorting
supes = []
bats = []
wonder = []
flash = []
cap = []
for entry in heroes:
if heroes[entry] == superheroes[0]:
bats.append(entry)
elif heroes[entry] == superheroes[1]:
cap.append(entry)
elif heroes[entry] == superheroes[2]:
flash.append(entry)
elif heroes[entry] == superheroes[3]:
supes.append(entry)
else:
wonder.append(entry)
print("People Saved: ")
print("Batman ", sum(bats))
print("Captain America ", sum(cap))
print("Flash ", sum(flash))
print("Superman ", sum(supes))
print("Wonderwoman ", sum(wonder))
After this, I would have to find a method to put these values into a new dictionary. My task is to sum the keys and only have the values shown once. Meaning that all the people they saved must be a single integer value that can then be summed together with another dictionary like this.
How can I sum all the keys of each unique value together and display them within the dictionary? I can only use vanilla Python 3.x code and no other modules can be imported.
Upvotes: 0
Views: 48
Reputation: 2566
I am not sure to get the full picture of your question. You are looking for a way to sum all the key and display them as a dictionary where the key would be the value of your input and the value would be the sum of the key of your input.
Would this be helpful
input = {1867: 'Superman', 2904: 'Batman', 783: 'Wonderwoman', 4637: 'Superman', 8392: 'Batman'}
output = {v:k for k, v in input.items()}
This produce
>>> {'Superman': 4637, 'Batman': 8392, 'Wonderwoman': 783}
Upvotes: 0