Python Forum
Dictionary from a list failed, help needed
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary from a list failed, help needed
#1
Hi,

I am trying to get a dictionary from a list like ["a", "b", "c", "a", "c"]. The out come is expected to be {"a": [0, 3], "b": [1], "c": [2, 4]}. The element of the list is the key and index of the element is the value. My script below doesn't work. Need some help with why it doesn't work and a solution. Thanks!

l = ["a","b","c","a","c"]

#create a dictionary with l's elements
d ={}.fromkeys(l, [])


#assign key and value by for loop
enum = enumerate(l)
for i,j in enum:
    d[j].append(i)
    
print d
Reply
#2
Line4 is a problem. It assumes there is a single default value and assigns that to each. In your case that means each key is assigned the same empty list. When any key is updated, all the keys get updated because they're sharing the same list.

There are several ways to do this, but I might use setdefault(). I would append the position to the output of setdefault(). It will be the list if it already exists, or an empty list if it doesn't.

Your print line doesn't have parentheses. Are you running this under python2 or python3?

l = ["a","b","c","a","c"]

#create a dictionary
d = {}

#assign key and value by for loop
enum = enumerate(l)
for i,j in enum:
    d.setdefault(j, []).append(i)

print (d)
Output:
{'a': [0, 3], 'b': [1], 'c': [2, 4]}
leoahum likes this post
Reply
#3
Thanks a lot. It is super helpful! FYI, I'm using Ironpython 2.7 that embeded in some other software.

(Apr-26-2022, 08:58 PM)bowlofred Wrote: Line4 is a problem. It assumes there is a single default value and assigns that to each. In your case that means each key is assigned the same empty list. When any key is updated, all the keys get updated because they're sharing the same list.

There are several ways to do this, but I might use setdefault(). I would append the position to the output of setdefault(). It will be the list if it already exists, or an empty list if it doesn't.

Your print line doesn't have parentheses. Are you running this under python2 or python3?

l = ["a","b","c","a","c"]

#create a dictionary
d = {}

#assign key and value by for loop
enum = enumerate(l)
for i,j in enum:
    d.setdefault(j, []).append(i)

print (d)
Output:
{'a': [0, 3], 'b': [1], 'c': [2, 4]}
Reply
#4
I don't know anything about dict.setdefault() or where it might be useful.

You could achieve the same result like this:

mylist = ["a", "b", "c", "a", "c"]
# make a dictionary of empty lists
mydict = {l:[] for l in mylist}
# populate the lists
for v, k in enumerate(mylist):
    mydict[k].append(v)
How to put these 2 steps in a one-liner, I don't know!
leoahum likes this post
Reply
#5
This is not easy to read:
l = ["a","b","c","a","c"]
d = {key:[index for index, value in enumerate(l) if value == key] for key in l}
print (d)
Output:
{'a': [0, 3], 'b': [1], 'c': [2, 4]}
leoahum and Pedroski55 like this post
Reply
#6
Very cool! Well done!

I would never have figured thatt out!
Reply
#7
Thank you all for the wonderful solutions!
Reply
#8
Just for sake of completeness, to mention collections.defaultdict

from collections import defaultdict
mylist = ["a", "b", "c", "a", "c"]
result = defaultdict(list)
for idx, item in enumerate(mylist):
    result[item].append(idx)
print(result)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  check if element is in a list in a dictionary value ambrozote 4 601 May-11-2022, 06:05 PM
Last Post: deanhystad
  how to assign items from a list to a dictionary CompleteNewb 3 632 Mar-19-2022, 01:25 AM
Last Post: deanhystad
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 1,011 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Class-Aggregation and creating a list/dictionary IoannisDem 1 948 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  Python dictionary with values as list to CSV Sritej26 4 1,727 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  convert List with dictionaries to a single dictionary iamaghost 3 1,752 Jan-22-2021, 03:56 PM
Last Post: iamaghost
Sad Convert python list to dictionary akanowhere 6 2,161 Dec-27-2020, 09:26 PM
Last Post: Pedroski55
  Creating a dictionary from a list Inkanus 5 2,030 Nov-06-2020, 06:11 PM
Last Post: DeaD_EyE
  Dictionary list coja56 7 1,832 Sep-20-2020, 03:53 PM
Last Post: deanhystad
  How to make a list of values from a dictionary list? faryad13 2 1,272 Sep-03-2020, 03:45 PM
Last Post: faryad13

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020