0
votes

I am having trouble converting a 2d list into a 2d dictionary. I haven't worked much with 2d dictionaries prior to this so please bear with me. I am just wondering why this keeps pulling up a KeyError. In this quick example I would want the dictionary to look like {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]]

I keep getting the error message: KeyError: 'male'. I know this is how you add keys for a 1d dictionary, but am unsure regarding 2d dictionaries. I always believed it was:

    dictionary_name[key1][key2] = value
6
Could you share a sample of your expected result?voidpro
Preferably with three samples instead of two, as it will better illustrate your challenge. HINT: You can't have duplicate keys.Alexander
well, you can't have a variable named 2dList anyway.Rahul K
by the way if your question is answered it'll be great if you accept the most helpful answer :) stackoverflow.com/help/someone-answerschowsai

6 Answers

1
votes

You can try this :) It will also work if you have more than one male or female in your 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]}
1
votes

You are attempting to build a nested dictionary. But are not explicitly initializing the second-layer dictionaries. You need to do this each time, a new key is encountered. Btw, 2dlist is an erroneous way to declare variables in python. This should work for you:

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
votes

To get more or less "sane" result use the following (list of dictionaries, each dict is in format {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)

The output:

[{'male': {'josh': ['chicken', 'purple', '10']}}, {'female': {'Jenny': ['steak', 'blue', '11']}}]
0
votes

You are getting a KeyError because you are trying to access a non-existing entry on the dictionary with male as the key

You can use defaultdict instead of 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]]
0
votes

Try this

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))}

As someone mentioned in the comments, you cannot have a variable starting with a number.

0
votes
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

Above one gives below output: {"male":{"josh":["chicken","purple","10"],"johnson":["chicken","purple","10"]},"female":{"jenniffer":["steak","blue","11"],"Jenny":["steak","blue","11"]}}