[英]How to iterate over list of sets and converting it to a dictionary in Python3
I have an input in the following format and I need to traverse through it to convert the given set into a dictionary.我有以下格式的输入,我需要遍历它以将给定的集合转换为字典。
input = [{"Bob","87"}, {"Mike", "35"},{"Bob", "52"}, {"Jason","35"}, {"Mike", "55"}, {"Jessica", "99"}]
My end goal is to have the average of every student in the dictionary form.我的最终目标是让每个学生的平均数以字典的形式出现。
I tried doing it:我试着这样做:
marks_dict ={}
for k,v in marks:
if k not in marks_dict.keys():
marks_dict[k] = v
else:
marks_dict[k].append(v)
print(marks_dict.keys())```
I am getting in output:
'87': 'Bob', '35': 'Mike', '52': 'Bob', 'Jason': '35', 'Mike': '55', '99': 'Jessica'}
sometimes :
Traceback (most recent call last):
File "/Users/rbhutada/Desktop/GSTest.gyp", line 7, in <module>
marks_dict[k].append(v)
AttributeError: 'str' object has no attribute 'append'
Sets are by definition unordered.根据定义,集合是无序的。 So
{"Bob", "87"}
is identical to {"87", "Bob"}
.所以
{"Bob", "87"}
与{"87", "Bob"}
相同。
So you don't want to use sets.所以你不想使用集合。 Use tuples (or lists) instead, as they are ordered:
改用元组(或列表),因为它们是有序的:
input = [("Bob","87"), ("Mike", "35"),("Bob", "52"), ("Jason","35"), ("Mike", "55"), ("Jessica", "99")]
Also, when you initialize a key, use a list [v]
instead of the scalar v
:此外,当您初始化密钥时,请使用列表
[v]
而不是标量v
:
if k not in marks_dict.keys():
marks_dict[k] = [v]
Otherwise you cannot append to it later.否则你以后不能给它 append。
So the code becomes (with input
changed to marks
so it fits with the code):所以代码变成了(
input
更改为marks
,因此它适合代码):
marks = [("Bob","87"), ("Mike", "35"),("Bob", "52"), ("Jason","35"), ("Mike", "55"), ("Jessica", "99")]
marks_dict ={}
for k,v in marks:
if k not in marks_dict.keys():
marks_dict[k] = [v]
else:
marks_dict[k].append(v)
print(marks_dict.keys())
print(marks_dict)
with this output:有了这个 output:
dict_keys(['Bob', 'Mike', 'Jason', 'Jessica'])
{'Bob': ['87', '52'], 'Mike': ['35', '55'], 'Jason': ['35'], 'Jessica': ['99']}
From there I will leave it to you to calculate the averages.从那里我会留给你计算平均值。
I do suggest using integers from the beginning for the marks, though, instead of strings, if they are all integers.不过,我确实建议从一开始就使用整数作为标记,而不是字符串,如果它们都是整数的话。 So
87
instead of "87"
, for instance.例如,所以
87
而不是"87"
。
If you really happen to have sets in a list, you need to convert it to an easier to handle data type before.如果你真的碰巧在列表中有集合,你需要先把它转换成更容易处理的数据类型。 Afterwards, you may use
itertools.groupby
:之后,您可以使用
itertools.groupby
:
from itertools import groupby
lst = [{"Bob", "87"}, {"Mike", "35"}, {"Bob", "52"}, {"Jason", "35"}, {"Mike", "55"}, {"Jessica", "99"}]
def convert(item):
""" Convert it to a tuple instead. """
x, y = item
if x.isdigit():
return y, x
else:
return x, y
lst = sorted(map(convert, lst), key=lambda item: item[0])
result = {}
for name, values in groupby(lst, key=lambda item: item[0]):
marks = [int(x[1]) for x in values]
result[name] = sum(marks) / len(marks)
print(result)
Which results in结果是
{'Bob': 69.5, 'Jason': 35.0, 'Jessica': 99.0, 'Mike': 45.0}
But don't use sets in the first place and don't use variable names like input
, dict
or list
.但是首先不要使用集合,也不要使用像
input
、 dict
或list
这样的变量名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.