使用重复值对词典中的唯一整数求和

时间:2018-03-09 03:23:18

标签: python-3.x dictionary

我打开了一个.txt文件,并使用.readlines方法转换为列表。

with open('superheroes.txt') as f:
    hero = f.readlines()

我把它读成一个空字典,因为该文件有很多重复的字符串但只有唯一的数字,我选择使用这个代码将唯一的整数设为键,重复的字符串使用这些代码:

heroes = {}

for i in range(len(hero)):
    name, num = hero[i].strip().split("\t")

    heroes[int(num)] = name

print语句的输出给出了类似的内容:

{1867:'超人',2904:'蝙蝠侠',783:'神奇女侠',4637:'超人',8392:'蝙蝠侠'等}}

到目前为止,我能够将特定值的所有键附加到唯一列表中,并使用for循环和if语句手动对它们进行排序:

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))

在此之后,我将不得不找到一种方法将这些值放入新的字典中。我的任务是对键求和,只显示一次值。这意味着他们保存的所有人必须是一个整数值,然后可以将其与另一个这样的字典一起求和。

如何将每个唯一值的所有键相加并在字典中显示?我只能使用vanilla Python 3.x代码,不能导入其他模块。

1 个答案:

答案 0 :(得分:0)

我不确定能够全面了解您的问题。您正在寻找一种方法来对所有键求和并将它们显示为字典,其中键是输入的值,值将是输入键的总和。

这会有用吗

input = {1867: 'Superman', 2904: 'Batman', 783: 'Wonderwoman', 4637: 'Superman', 8392: 'Batman'}
output = {v:k for k, v in input.items()}

这个产品

>>> {'Superman': 4637, 'Batman': 8392, 'Wonderwoman': 783}