Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k points)

I'm having troubles in populating a python dictionary starting from another dictionary.

Let's assume that the "source" dictionary has a string as keys and has a list of custom objects per value.

I'm creating my target dictionary exactly as I have been creating my "source" dictionary how is it possible this is not working?

I get

TypeError: unhashable type: 'list'

Code :

aTargetDictionary = {} 

for aKey in aSourceDictionary: 

 aTargetDictionary[aKey] = [] 

 aTargetDictionary[aKey].extend(aSourceDictionary[aKey])

The error is on this line : aTargetDictionary[aKey] = []

1 Answer

0 votes
by (106k points)

The error you are getting because things don't add up. If aSourceDictionary is a dictionary, then your for loop has to work properly.

>>> source = {'a': [1, 2], 'b': [2, 3]} 

>>> target = {} 

>>>for key in source: 

... target[key] = [] 

... target[key].extend(source[key]) 

... 

>>> target 

{'a': [1, 2], 'b': [2, 3]} 

>>>

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 15, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
asked Sep 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...