0

I want to create a loop to generate a dictionary with for each key 5 lists with each three values. And add edit the last value of list 2 and 3 based on the key of the dictionary and the index of the list (so list 2 and 3).

I tried the following code but get the error message: 'cannot unpack non-iterable int object'

# Create dicitonairy with 6 empty lists
dict_of_lists = dict.fromkeys(range(0,6),[])
for key, value in dict_of_lists:
    # Create 5 lists with the list number as the first value
    for li in range(5):
        dict_of_lists[key] = [li,0,0]
    # Edit the last value of list 1 and 2 (index)
    for wi in [1,2]:
        dict_of_lists[wi][2] = item[wi]*price[key]

What is the best way to create the following output:

{
0:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
1:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
2:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
3:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
4:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
5:[[0,0,0],[1,0,x],[2,0,x],[3,0,0],[4,0,0]]
}

Where x is a value based on the list where it's in (1 to 5) and the key of the dictionary.

3 Answers 3

2
dict_of_lists = dict.fromkeys(range(0,6),[])
for key, value in dict_of_lists.items():
    # Create 5 lists with the list number as the first value
    l = []
    for li in range(5):
        if li == 1 or li == 2:
            # l.append([li, 0, li*key]) 
            l.append([li, 0, 'x'])
        else:
            l.append([li,0,0])
    dict_of_lists[key] = l
print (dict_of_lists)

output:

{0: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
1: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
2: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
3: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
4: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]], 
5: [[0, 0, 0], [1, 0, 'x'], [2, 0, 'x'], [3, 0, 0], [4, 0, 0]]}
Sign up to request clarification or add additional context in comments.

Comments

1

To iterate over a dictionary you need to use dict.items().

In your case:

for key, value in dict_of_lists.items():
    #code

Comments

0

You are iterating through a dict wrongly. If you want to iterate with both key and value specified inside the loop (like in yours), you should iterate through dict items, because a usual iteration iterates through dict keys. So you should change your line to:

for key, value in dict_of_lists.items():

(PS: There are unspecified item and price in the last line, I suppose you specified them before this block)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.