在python中将多列表转换为字典
我正在尝试从列表列表创建词典。我有一个姓名和标记列表,如:在python中将多列表转换为字典,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我正在尝试从列表列表创建词典。我有一个姓名和标记列表,如: str=[ ["Amit", 23], ["Amit", 127], ["Rahul", 3], ["Rahul", 71], ["Deepak", 31], ["Rahul", 22], ["Amit", 81] ] 使用键作为名称,值作为平均标记的字典,如: {"Amit":77, "Rahul":32, "Deepak":31} 我试图获取每个列表,然后将其转换为字典值。但是我犯了一个错误 def highest_avg(st
str=[
["Amit", 23],
["Amit", 127],
["Rahul", 3],
["Rahul", 71],
["Deepak", 31],
["Rahul", 22],
["Amit", 81]
]
使用键作为名称,值作为平均标记的字典,如:
{"Amit":77, "Rahul":32, "Deepak":31}
我试图获取每个列表,然后将其转换为字典值。但是我犯了一个错误
def highest_avg(str):
mydict={}
for each in str:
my_dict=dict.fromkeys(each[0],each[1])
print(my_dict)
一,。使用键存储编号的列表
#驱动程序值:
IN :s = [['Amit', 23], ['Amit', 127], ['Rahul', 3], ['Rahul', 71],
['Deepak', 31], ['Rahul', 22], ['Amit', 81]]
我会使用列表的OrderedDict
,因为看起来您希望维护顺序
from collections import OrderedDict
o = collections.OrderedDict()
for i in data:
o.setdefault(i[0], []).append(i[1])
现在已经完成了向字典中添加数据,请按键计算平均值
for k in o:
o[k] = sum(o[k]) / len(o[k])
如果顺序在这里不是最重要的,那么一本普通的{}
字典也可以
使用列表理解:
{x[0]:x[1] for x in str}
或将数据分为两个列表键和值:
keys = [x[0] for x in str]
values = [x[1] for x in str]
dict(zip(keys, values))
输出:
{'Deepak': 31, 'Amit': 81, 'Rahul': 22}
使用标准Python方法:
myList=[
["Amit", 23],
["Amit", 127],
["Rahul", 3],
["Rahul", 71],
["Deepak", 31],
["Rahul", 22],
["Amit", 81]
]
myDict = dict()
for key, value in myList:
if key not in myDict:
myDict[key] = list()
myDict[key].append(value)
for key, values in myDict.items():
myDict[key] = sum(values) / len(values)
print(myDict)
首先,我得到属于某个键的所有值,然后计算平均值。还要注意str是一个内置变量,所以我用myList替换了它。您可以使用itertools.groupby
:
from itertools import groupby
k = lambda x: x[0]
{k: sum(l)//len(l) for k, l in ((k, [x[1] for x in g]) for k, g in groupby(sorted(str, key=k), key=k))}
# {'Amit': 77, 'Deepak': 31, 'Rahul': 32}
希望这有帮助这不是OP的要求。即使期望的输出也不匹配。请把这个问题再复习一遍。
keys = [x[0] for x in str]
values = [x[1] for x in str]
dict(zip(keys, values))
{'Deepak': 31, 'Amit': 81, 'Rahul': 22}
myList=[
["Amit", 23],
["Amit", 127],
["Rahul", 3],
["Rahul", 71],
["Deepak", 31],
["Rahul", 22],
["Amit", 81]
]
myDict = dict()
for key, value in myList:
if key not in myDict:
myDict[key] = list()
myDict[key].append(value)
for key, values in myDict.items():
myDict[key] = sum(values) / len(values)
print(myDict)
from itertools import groupby
k = lambda x: x[0]
{k: sum(l)//len(l) for k, l in ((k, [x[1] for x in g]) for k, g in groupby(sorted(str, key=k), key=k))}
# {'Amit': 77, 'Deepak': 31, 'Rahul': 32}
data =[
["Amit", 23],
["Amit", 127],
["Rahul", 3],
["Rahul", 71],
["Deepak", 31],
["Rahul", 22],
["Amit", 81]
]
import numpy as np
import pandas as pd
data_df = pd.DataFrame(data) #convert your list into a Pandas DataFrame
data_df
0 1
0 Amit 23
1 Amit 127
2 Rahul 3
3 Rahul 71
4 Deepak 31
5 Rahul 22
6 Amit 81
agg_data = data_df.groupby(data_df[0]).agg(np.mean) #Group data on names & aggregate using mean of scores(values)
agg_data
1
0
Amit 77
Deepak 31
Rahul 32
agg_data.to_dict()[1] #Convert your Pandas DataFrame into dict using 'dict' orientation
#the [1] is the key that represents your column. Dict is created like this: {column -> {index -> value}}
{'Amit': 77, 'Deepak': 31, 'Rahul': 32} #This is the output