Reputation: 340
I'm attempting to iterate through a list and if the list item equals a dictionary key, append the list item to the dictionary.
mylist = [1, 2, 3]
mydict = dict.fromkeys(mylist, [])
for item in mylist:
for key in mydict:
if key == item:
mydict[key].append(item)
print(mydict)
Output:
{1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 3]}
Required output:
{1: [1], 2: [2], 3: [3]}
Much thanks!
Upvotes: 2
Views: 1664
Reputation: 17322
by using:
mylist = [1, 2, 3]
mydict = dict.fromkeys(mylist, [])
you are creating a dict that has all the elements from mylist
as keys and all the values from your dict are references to the same list, to fix you may use:
mydict = dict.fromkeys(mylist)
for item in mylist:
mydict[item] = [item]
print(mydict)
output:
{1: [1], 2: [2], 3: [3]}
same thing but in a more efficient and compact form by using a dictionary comprehension:
mydict = {item: [item] for item in mylist}
Upvotes: 1
Reputation: 327
mylist = [1, 2, 3]
mydict = dict.fromkeys(mylist, [])
for item in mylist:
for key in mydict:
if key == item:
mydict[key] = [item]
print(mydict)
Upvotes: 0
Reputation: 421
Is this what you wanted?
mylist = [1,2,3,3]
mydict = {}
for item in mylist:
if item not in mydict:
mydict[item] = [item]
else:
mydict[item].append(item)
print(mydict)
It will output: {1: [1], 2: [2], 3: [3, 3]}
Upvotes: 0
Reputation: 44838
That's because here:
mydict = dict.fromkeys(mylist, [])
mydict
's values will be the same object []
, so when you append to mydict[something]
, you'll be appending to the same list, no matter what something
is.
All values are the same object, you append three numbers to it => all values are shown as the same list.
To avoid this, assign new lists to each key:
mydict = {}
for item in mylist:
mydict.setdefault(item, []).append(item)
Or, you know:
mydict = {key: [key] for key in mylist}
Upvotes: 4