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
  Dictionary in a list bashage 2 493 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 597 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Sort a list of dictionaries by the only dictionary key Calab 1 452 Oct-27-2023, 03:03 PM
Last Post: buran
  How to add list to dictionary? Kull_Khan 3 951 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  check if element is in a list in a dictionary value ambrozote 4 1,879 May-11-2022, 06:05 PM
Last Post: deanhystad
  how to assign items from a list to a dictionary CompleteNewb 3 1,535 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 2,523 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,881 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  Python dictionary with values as list to CSV Sritej26 4 2,955 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  convert List with dictionaries to a single dictionary iamaghost 3 2,800 Jan-22-2021, 03:56 PM
Last Post: iamaghost

Forum Jump:

User Panel Messages

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