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
#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


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

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