Python Forum
create empty sets for keys in a dictionary and add values to the set
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
create empty sets for keys in a dictionary and add values to the set
#1
so what I wanna do is this but something cleaner(short):
dic = {}
if key0 not in dic.keys():
	dic[key0] = set()
	dic[key0].add(2)
else:
	dic[key0].add(2)
What I really wanted was to run a loop and add values (to the set) for the corresponding keys if it(key) exists, and if not create one(key with an empty set) and add then.

In an another attempt one could create dictionary beforehand with all values being empty sets. then just add to the value(to the set) without using if-else:
dic = {key0: set(), key1: set(), key2: set()}
dic[key0].add(2)
But this would be an issue if I don't know what the keys would be. Again I wanna do this in a loop for multiple keys & values. This is just a simpler version of my problem.

EDIT: did some searching this should be it.
dic.setdefault(key0, set())
dic[key0].add(2)
EDIT0: collections.defaultdict is perfect
Reply
#2
collections.defaultdict can help.

from collections import defaultdict

setdict = defaultdict(set)
setdict[42].add(1337)
setdict[0].add("Foo")

print(setdict)
naughtysensei likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how can i create a dictionary of dictionaries from a file Astone 2 2,262 Oct-26-2020, 02:40 PM
Last Post: DeaD_EyE
  Why is this function printing the number of keys in a dictionary? mafr97 5 3,055 Sep-17-2019, 06:19 AM
Last Post: perfringo
  Accessing nested keys and values in Dictreader cartographer72 2 2,395 Mar-08-2019, 03:55 AM
Last Post: cartographer72
  Take use input in sets and Dictionaries usman 4 3,161 Nov-18-2018, 01:54 PM
Last Post: usman
  Issues with Inserting Values into an Empty List with a While Loop TommyMer 2 3,778 Sep-12-2018, 12:43 AM
Last Post: TommyMer
  Looping to Create Nested Dictionary gngu2691 10 33,551 Jun-22-2018, 04:11 PM
Last Post: anickone
  logic comparater based on dictionary values ijosefson 3 3,241 Oct-16-2017, 06:04 AM
Last Post: Mekire

Forum Jump:

User Panel Messages

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