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


Messages In This Thread
Dictionary from a list failed, help needed - by leoahum - Apr-26-2022, 08:39 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Dictionary in a list bashage 2 541 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 666 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  Sort a list of dictionaries by the only dictionary key Calab 1 488 Oct-27-2023, 03:03 PM
Last Post: buran
  How to add list to dictionary? Kull_Khan 3 998 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  check if element is in a list in a dictionary value ambrozote 4 1,963 May-11-2022, 06:05 PM
Last Post: deanhystad
  how to assign items from a list to a dictionary CompleteNewb 3 1,567 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,596 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,917 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  Python dictionary with values as list to CSV Sritej26 4 2,996 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  convert List with dictionaries to a single dictionary iamaghost 3 2,857 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