2

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!

Marla
  • 340
  • 3
  • 16
  • If `mylist=[1,2,3,3]`,`mydict={1:[1],2:[2],3:[3,3]}`? – jizhihaoSAMA Apr 10 '20 at 15:50
  • Does this answer your question? [Dictionary creation with fromkeys and mutable objects. A surprise](https://stackoverflow.com/questions/8174723/dictionary-creation-with-fromkeys-and-mutable-objects-a-surprise) – AMC Apr 10 '20 at 17:16

4 Answers4

4

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}
ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

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}
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

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]}

Yosua
  • 411
  • 3
  • 7
0
mylist = [1, 2, 3]

mydict = dict.fromkeys(mylist, [])

for item in mylist:
    for key in mydict:
        if key == item:
            mydict[key] = [item]

print(mydict)
Eduardo Donato
  • 147
  • 2
  • 10
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Apr 11 '20 at 06:45