我正在尝试将多个词典转换为单个列表,例如
for data in result:
dic = { "student_names" : str(data[1]),
"student_department" : str(data[7])}
print dic
输出
{'student_names': 'Shahroz Akbar', 'student_department': 'computer science'}
{'student_names': 'Ahsan Mehmood', 'student_department': 'computer science'}
{'student_names': 'Hamza Anwar', 'student_department': 'computer science'}
我想这样转换
list1 = [{'student_names': 'Shahroz Akbar', 'student_department': 'computer science'},
{'student_names': 'Ahsan Mehmood', 'student_department': 'computer science '},
'student_names': 'Hamza Anwar', 'student_department': 'computer science'}]
答案 0 :(得分:0)
将每个字典作为一个项目存储在列表中与您拥有的非常相似。无需打印信息,您只需将每个项目.append()
放入列表中。
list1 = []
for data in result:
dic = { "student_names" : str(data[1]), "student_department" : str(data[7])}
list1.append(dic)
也许您应该review how lists work in python
您也可以将其压缩为一行,例如:
list1 = []
for data in result:
list1.append({"student_names": str(data[1]), "student_department": str(data[7])})
答案 1 :(得分:0)
您可以:
list1 = []
for data in result:
dic = { "student_names" : str(data[1]),
"student_department" : str(data[7])}
list1.append(dic)
但是您也许应该考虑使用pandas DataFrame
来做到这一点:
import pandas as pd
values = []
for data in result:
values.append([str(data[1]), str(data[7])])
df = pd.DataFrame(values, columns=["student_names", "student_department"])