This is my code:
diction = {}
for i in range (5):
key = "key"
diction[key] = {str(i)}
print (diction)
The printed result, obviously, would be this:
{'key': {'4'}}.
How can I change the code so I can have this as the output:
{'key': {'0','1','2','3','4'}}
In order to add a value to a set, you should use the .add
method. For the initial case (i=1), you should also check if the key has been set in the dictionary so you don't add to an inexistent set and get an error:
Accordingly, your new code would be:
diction = {}
for i in range (5):
key = "key"
if key not in diction:
diction[key] = {i}
else:
diction[key].add(i)
The result of :
print (diction)
is now
{'key': {0, 1, 2, 3, 4}}
.add()
to the set?
diction = {'key': set()}
for i in range(5):
diction['key'].add(str(i))
print(diction['key'])
EDIT :
diction = {}
for i in range(5):
k = 'key'+str(i*2)
if not k in diction:
diction[k] = set()
diction[k].add(str(i))
print(diction)
A list comprehension should be WAY better:
diction = {'key': set(map(str,range(5)))}
Probably the two most common ways to do this in Python is by using either the dict.setdefault()
method or the collections.defaultdict
dictionary subclass.
Both make it easy to modify the value of existing entries without checking to see if it's the first time the key has been seen. Below are examples of doing it both ways.
setdefault()
: diction = {}
for i in range (5):
key = "key"
diction.setdefault(key, set()).add(str(i))
print(diction)
defaultdict
: from collections import defaultdict
diction = defaultdict(set)
for i in range (5):
key = "key"
diction[key].add(str(i))
print(diction)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.