Python 我能';t从excel文件创建字典列表
这是我的密码。我读了一个带熊猫的excel文件Python 我能';t从excel文件创建字典列表,python,list,dictionary,Python,List,Dictionary,这是我的密码。我读了一个带熊猫的excel文件 import pandas as pd df = pd.read_excel('people.xlsx') print(df.to_dict()) user = {} list_of_user = [] for i in range(len(df)): user['name'] = (df['name'][i]) user['surname'] =
import pandas as pd
df = pd.read_excel('people.xlsx')
print(df.to_dict())
user = {}
list_of_user = []
for i in range(len(df)):
user['name'] = (df['name'][i])
user['surname'] = (df['surname'][i])
user['email'] = (df['email'][i])
user['interest'] = (df['interest'][i])
print(user)
list_of_user.append(user)
print(list_of_user)
这就是结果
{'name': {0: 'John', 1: 'Marry', 2: 'Dmitri'}, 'surname': {0: 'Smith', 1: 'Smith', 2: 'Kery'}, 'email': {0: 'a@com', 1: 'a1@com', 2: 'a2@com'}, 'interest': {0: 'money', 1: 'gadget', 2: 'nasa'}}
user = {'name': 'John', 'surname': 'Smith', 'email': 'a@com', 'interest': 'money'}
user = {'name': 'Marry', 'surname': 'Smith', 'email': 'a1@com', 'interest': 'gadget'}
user = {'name': 'Dmitri', 'surname': 'Kery', 'email': 'a2@com', 'interest': 'nasa'}
list_of_user = [{'name': 'Dmitri', 'surname': 'Kery', 'email': 'a2@com', 'interest': 'nasa'}, {'name': 'Dmitri', 'surname': 'Kery', 'email': 'a2@com', 'interest': 'nasa'}, {'name': 'Dmitri', 'surname': 'Kery', 'email': 'a2@com', 'interest': 'nasa'}]
为什么在用户列表中我有3个相同的用户?您可以尝试使用:
_user.append({user.items()})的列表
相反。您正在重用用户变量,而无需重新初始化它。字典变量是引用,而不是值。因此,这就像拥有
[用户,用户,用户]
其中用户是相同的东西。谢谢。我将user={}添加到循环及其工作的开头。我尝试了,但出现了一个错误。TypeError:Unhabable类型:“dict_items”在尝试将np.array列表添加到列表时遇到了几乎相同的问题。。。我们问题的根源是dict和list是可变类型。因此,最可靠的(我想)解决方案是使用.copy()方法:list\u of_user.append(user.copy())。