Search code examples
pythondictionary-comprehension

Is there a way to self generate similar key names and values in a dictionary with a loop?


I want to create a dictionary by using a loop or similar technique. Something like the below variable assignment is possible.

my_dict = {v:int(v*random()) for v in range(10)}

Though the question I am stuck at- How can I generate similar names for the item keys? Giving an example below:

{'Item-1': 1, 'Item-2':3, 'Item-3':3 ....} 

Thanks in advance!


Solution

  • from random import random
    
    my_dict = {f'item-{v+1}': int(v*random()) for v in range(10)}
    print(my_dict)
    

    Output:

    {'item-1': 0, 'item-2': 0, 'item-3': 1, 'item-4': 1, 'item-5': 0, 'item-6': 3, 'item-7': 2, 'item-8': 4, 'item-9': 6, 'item-10': 2}

    This uses an f-string to create the key, the corresponding value is randomly generated like in your question.