user13380206
user13380206

Reputation:

Python Dictionary - Key Assignment by iterations

I am new to python and I have created the following dictionary:

workers = ['Thomas', 'Jack',  'Charles', 'Peter']

GrpList = {('Task {1}'.format for i in range(1,3)): workers}

And the output is:

{<generator object <genexpr> at 0x000001AF99B861C8>: ['Thomas','Jack','Charles','Peter']}

How can I modify my codes (in a single line) so that the result can be:

{'Task 1': ['Thomas','Jack','Charles','Peter'],
 'Task 2': ['Thomas','Jack','Charles','Peter'],
 'Task 3': ['Thomas','Jack','Charles','Peter']}

instead of showing a generator expression in the dictionary keys.

Upvotes: 0

Views: 37

Answers (3)

Dani Mesejo
Dani Mesejo

Reputation: 61920

You have a problem with your dictionary comprehension, do this:

workers = ['Thomas', 'Jack', 'Charles', 'Peter']

GrpList = {f'Task {i}': workers for i in range(1, 4)}

print(GrpList)

The idea is to use range to generate the keys, the values are all the same. As an alternative you could use dict.fromkeys:

GrpList = dict.fromkeys((f'Task {i}' for i in range(1, 4)), workers)

Output

{'Task 1': ['Thomas', 'Jack', 'Charles', 'Peter'], 'Task 2': ['Thomas', 'Jack', 'Charles', 'Peter'], 'Task 3': ['Thomas', 'Jack', 'Charles', 'Peter']}

Observations

1) All the keys refer to the same list, if you want the keys to refer to equal values, but not the same, do this instead:

GrpList = {f'Task {i}': workers[:] for i in range(1, 4)}

2) The name GrpList, suggest a list but the actual value is a dictionary, perhaps using another name, such as GrpDict, would be better.

Upvotes: 1

user13051721
user13051721

Reputation:

It is simple, you can achieve your purpose using this code:

grp_list = {"Task {}".format(i+1): workers for i in range(0, len(workers))}

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

You forgot to pass the argument to format:

GrpList = {'Task {}'.format(i) : workers for i in range(1,4)}

Upvotes: 0

Related Questions