简体   繁体   中英

How do I counter value in a for loop as part of my dictionary key

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"

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)}

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"

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'}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM