我无法将2d列表转换为2d字典。在此之前我没有使用过2d词典,所以请耐心等待。我只是想知道为什么这会持续引发KeyError。在这个快速示例中,我希望字典看起来像{gender:{name:[food,color,number]}}
2dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = {}
for i in range(len(2dList)):
dict[2dList[i][0]][2dList[i][1]] = [2dList[i][2], 2dList[i][3], 2dList[i][4]]
我不断收到错误消息: KeyError:'male'。我知道这是你为1d字典添加密钥的方法,但我不确定2d字典。我一直相信它是:
dictionary_name[key1][key2] = value
答案 0 :(得分:1)
您正在尝试构建嵌套字典。但是没有明确初始化第二层词典。每次都需要执行此操作,遇到新密钥。顺便说一句,2dlist
是一种在python中声明变量的错误方法。这应该适合你:
dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = {}
for i in range(len(dList)):
if not dList[i][0] in dict.keys():
dict[dList[i][0]] = {}
dict[dList[i][0]][dList[i][1]] = [dList[i][2], dList[i][3], dList[i][4]]
print(dict)
答案 1 :(得分:1)
要获得更多或更少的“理智”结果,请使用以下(字典列表,每个字典的格式为{gender: { name: [food, color, number] }}
):
l = [['male','josh','chicken','purple','10'], ['female','Jenny','steak','blue','11']]
result = [{i[0]: {i[1]:i[2:]}} for i in l]
print(result)
输出:
[{'male': {'josh': ['chicken', 'purple', '10']}}, {'female': {'Jenny': ['steak', 'blue', '11']}}]
答案 2 :(得分:1)
你可以尝试这个:)如果你的male
female
或List
,它也会有效
List = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
d = {}
for l in List:
gender = l[0]
name = l[1]
food = l[2]
color = l[3]
number = l[4]
if gender in d: # if it exists just add new name by creating new key for name
d[gender][name] = [food,color,number]
else: # create new key for gender (male/female)
d[gender] = {name:[food,color,number]}
答案 3 :(得分:0)
您收到KeyError
,因为您尝试以male
作为关键字访问字典中的不存在条目
您可以使用defaultdict
代替dict
。
from collections import defaultdict
2dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = defaultdict(list)
for i in range(len(2dList)):
dict[2dList[i][0]][2dList[i][1]] = [2dList[i][2], 2dList[i][3], 2dList[i][4]]
答案 4 :(得分:0)
试试这个
twodList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dic = {twodList[i][0]: {twodList[i][1]: twodList[i][2:]} for i in range(len(twodList))}
正如评论中提到的那样,你不能有一个以数字开头的变量。
答案 5 :(得分:0)
list1=[['male','josh','chicken','purple','10'],['female','Jenny','steak','blue','11'],['male','johnson','chicken','purple','10'],['female','jenniffer','steak','blue','11']]
dict = {}
for i in range(len(list1)):
if list1[i][0] in dict:
if list1[i][1] in dict[list1[i][0]]:
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]][list1[i][1]] = {}
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]] = {}
if list1[i][1] in dict[list1[i][0]]:
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]][list1[i][1]] = {}
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
print dict
上面给出了以下输出: {"男性" {"约什":["鸡""紫"" 10&#34],& #34;约翰逊":["鸡""紫"" 10"]}"女性" {&# 34; jenniffer":["牛排""蓝色"" 11&#34],"珍妮":["牛排""蓝色"" 11"]}}