howto to join "only" values of a an element of a dictionary of two elements in python list

Viewed 36

Consider a list with dictionary members as follows:

txt1 = {
  'k1': 'val1',
  'k2': 14,
  'k3': 5,
  'A':[
       {'i1': 0, 'i2': 'value1'}, 
       {'i1': 2, 'i2': 'value2'}, 
       {'i1': 6, 'i2': 'value3'}, 
       {'i1': 9, 'i2': 'value4'}, 
       {'i1': 11, 'i2': 'value5'}
       ],
  't': 4,
  'l':-1,
  'a': 'G',
  'h': [],
  'd':[],
  'tp':[]}

What is the best way of getting a string composed of "value1 value2...value5". I know how to do it thru a loop? But I am wondering if there are short cuts to d so. Thanks for your help

3 Answers
ans = [d['i2'] for d in txt1['A']]
print(' '.join(ans))

Output: value1 value2 value3 value4 value5 I hope that's you want.

Use a list comprehension like:

value_list = [a['i2'] for a in txt1['A']]
Related