Reputation: 5
I want to take items from a list and put them into a dictionary.
Say we have the following
carList = set(zip(carWordList, carWordFreq))
note: I use set to remove duplicates
So carList would produce the following:
set([('merry', 3), ('cop', 25), ('completely', 21), ('jaw', 2), ('fiddle', 1), ('bright', 4), ('593', 1), ('asked', 22), ('additionally', 4), ('pretend', 1), ('beam', 4)])
Now I want to take the words (ex. 'merry') and make them keys in a dictionary (newDic) with the numbers as values.
Also, I want to use that new dictionary to create another dictionary (otherDic) that has two keys (one being the word (ex. 'merry') and another being "Car", which will take a value later
for key in newDic:
otherDic = [key]["Car"]
I tried to do the following:
for key in carList:
otherDic = [key]["Car"]
However, I get the following error:
TypeError: list indices must be integers, not str
Upvotes: 0
Views: 82
Reputation: 11932
When you do this
otherDic = [key]["Car"]
You are just creating a list [key]
that contains only key
, and then you are trying to index it with "Car"
instead of with an integer, which is why you get the error.
Secondly, you can't start looping into this for key in newDic:
without ever creating the newDic
which I don't see you doing at any point.
Anyway, this is the wrong way to approach your problem. To turn your set
into a dictionary you can simply do this:
my_dict = {key: value for key, value in carList}
That's called dictionary comprehension by the way. But as @Adam Smith pointed out, that is actually equivalent to
my_dict = dict(carList)
Which is simpler... But after that, I don't quite understand what you mean by creating another dict with 2 keys per value. You can't create a dict with 2 keys, that's not how they work. You could comment here on the desired output of this new dict and I will edit my answer.
Upvotes: 2
Reputation: 11550
You can use dictionary comprehension:
In [61]: l = set([('merry', 3), ('cop', 25), ('completely', 21), ('jaw', 2), ('fiddle', 1), ('bright', 4), ('593', 1), ('asked', 22), ('additionally', 4), ('pretend', 1), ('beam', 4)])
In [63]: d = {k:v for k,v in l}
In [64]: d
Out[64]:
{'593': 1,
'additionally': 4,
'asked': 22,
'beam': 4,
'bright': 4,
'completely': 21,
'cop': 25,
'fiddle': 1,
'jaw': 2,
'merry': 3,
'pretend': 1}
Upvotes: -1