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!

2
  • 1
    You can do {f'text_{a}': f'stuff_{a}' for a in aa} (from Python 3.6). Commented Jul 15, 2019 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. Commented Jul 15, 2019 at 15:20

2 Answers 2

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} 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.