0

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!

slim s
  • 107
  • 7
  • 1
    You can do `{f'text_{a}': f'stuff_{a}' for a in aa}` (from Python 3.6). – jdehesa Jul 15 '19 at 15:18
  • I would have done `dict(zip(("text_" + x for x in a), ("stuff " + x for x in a)))` but dict comprehension, as mentioned in the answers, is a better approach. – Ian Rehwinkel Jul 15 '19 at 15:20

2 Answers2

5

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}
Austin
  • 25,759
  • 4
  • 25
  • 48
3

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'}
abdusco
  • 9,700
  • 2
  • 27
  • 44