Is there a pythonic way to use items in a list to define a dictionary's key and values?
For example, I can do it with:
s = {}
a = ['aa', 'bb', 'cc']
for a in aa:
s['text_%s' %a] = 'stuff %s' %a
In [27]: s
Out[27]: {'text_aa': 'stuff aa', 'text_bb': 'stuff bb', 'text_cc': 'stuff cc'}
I wanted to know if its possible to iterate over the list with list comprehension or some other trick.
something like:
s[('text_' + a)] = ('stuff_' + a) for a in aa
thanks!
Use dictionary comprehension:
{'text_%s' %x: 'stuff %s' %x for x in a}
In newer versions:
{f'text_{x}': f'stuff {x}' for x in a}
You can use dictionary comprehensions:
a = ['aa', 'bb', 'cc']
my_dict = {f'key_{k}':f'val_{k}' for k in a}
print(my_dict)
output:
{'key_aa': 'val_aa', 'key_bb': 'val_bb', 'key_cc': 'val_cc'}
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.