2

I'm trying to create a dictionary where keys are strings and values are lists. Something like that

l1 = ['a', 'b', 'c']

and I want to add lists similar to that one in every iteration in a for loop.

I've tried this

dicc['first'].append(l1)

The exit should be something like that:

dicc={'first': ['a', 'b', 'c']}

I always get the same error: list indices must be integers or slices, not str

How can i do it?

2
  • Did you define dicc as a dictionary with something like dicc = {}? Commented Mar 17, 2019 at 16:47
  • from collections import defaultdict dicc = defaultdict(list) l1 = ['a', 'b', 'c'] for x in l1: dicc["first"].append(x) like this? Commented Mar 17, 2019 at 16:51

1 Answer 1

4

You have to assign the object in this case a list to the key in the dictionary, in your case:

dicc['first'] = l1

Sign up to request clarification or add additional context in comments.

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.