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

Time:09-11

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

CodePudding user response:

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

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

CodePudding user response:

Use a list comprehension like:

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

CodePudding user response:

my_list = [one_dict['i2'] for one_dict in txt1['A']]

>>> ['value1', 'value2', 'value3', 'value4', 'value5']

For more information on shorthands please refer to this guide on python generator expressions.

  • Related