I am trying to create a for loop that adds keys and values to a dictionary every time it loops. The counter value of this for loop is part of the key name that gets added to the dictionary every time. How can I code this without defining a separate set for key values and assigning them to key values? or better said, how can I remove this line? "y.insert(i, "This is key number " str(i 1))"
Here is my current code:
Dic = {}
y = []
for i in range(0,4):
y.insert(i, "This is key number " str(i 1))
Dic[y[i]] = "This is a constant value for all keys"
CodePudding user response:
You literally just insert
the new items at the last position of the list (for which you should use append
, but that's besides the point), just to then get the element at that index out of the list. Instead, you can just assign it to a temporary variable, without the list:
Dic = {}
for i in range(0,4):
x = "This is key number " str(i 1)
Dic[x] = "This is a constant value for all keys"
Of course, you don't really need that variable either, you can just put the expression into the [...]
(but it might be argued that the above is more readable):
Dic = {}
for i in range(0,4):
Dic["This is key number " str(i 1)] = "This is a constant value for all keys"
Which now can be directly translated to a dictionary comprehension:
Dic = {"This is key number " str(i 1): "This is a constant value for all keys" for i in range(0,4)}
After a bit of cleanup (note: f-strings require newer versions of Python, but there are other ways to format the number into the string without concatenation):
dic = {f"This is key number {i 1}": "This is a constant value for all keys" for i in range(4)}
CodePudding user response:
If you want to stick with something close to your starting for loop, just do:
Dic = {}
for i in range(0,4):
Dic[f"This is key number {i}"] = "This is a constant value for all keys"
CodePudding user response:
You can use the dict's fromkeys() method:
Dic = dict.fromkeys(map("This is key number {}".format,range(4)),"constant")
print(Dic)
{'This is key number 0': 'constant',
'This is key number 1': 'constant',
'This is key number 2': 'constant',
'This is key number 3': 'constant'}