简体   繁体   中英

Concatenate values in python dictionary

I have a python dictionary and I'd like to concatenate the values of value[0] and a list in value [1]

so

dict={       'Key1':['MASTER',['_A','_B','_C']]}

and expected output is of calling Key1 is

[['MASTER_A','MASTER_B','MASTER_C']]

Use a nested comprehension:

d = {'Key1':['MASTER',['_A','_B','_C']]}
result_dict = {k: [v[0] + l for l in v[1]] for k,v in d.items()}

For example:

>>> result_dict = {k: [v[0] + l for l in v[1]] for k,v in d.items()}
>>> result_dict
{'Key1': ['MASTER_A', 'MASTER_B', 'MASTER_C']}

Try this :

d = {'Key1':['MASTER',['_A','_B','_C']]}
out = [d['Key1'][0]+i for i in d['Key1'][1]]

Output :

['MASTER_A', 'MASTER_B', 'MASTER_C']

To assign it to the key, do :

d['Key1'] = out

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM