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

Question:

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

Asked By: Bid

||

Answers:

Use a list comprehension like:

value_list = [a['i2'] for a in txt1['A']]
Answered By: TheMaster
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.

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

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

Answered By: Chandler Bong
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.