Home > database >  How to extend an existing list with values of a dictionary as a string?
How to extend an existing list with values of a dictionary as a string?

Time:10-18

How to extend an existing list with values of a dictionary as a string in below Python codes?

x = [ 'h1', 'h2' ]

y = [ 'h3', 'h4' ]

dict_sample = {'xyz': ['ab', 'bc'], 'mno': ['cd', 'de']}

x.extend(dict_sample.keys()) ---> (Output) ['h1', 'h2', 'xyz', 'mno']

y.extend(dict_sample.values()) ----> (Output) ['h3', 'h4', ['ab', 'bc'], ['cd', 'de']]

However, how to obtain the below desired output for second case?

['h3', 'h4', '['ab', 'bc']', '['cd', 'de']']

CodePudding user response:

Assuming the desired output looks like ['h3', 'h4', '["ab", "bc"]', '["cd", "de"]'],
which includes stringified json elements, here's a way to do it:

import json

y = [ 'h3', 'h4' ]
dict_sample = {'xyz': ['ab', 'bc'], 'mno': ['cd', 'de']}

y.extend([json.dumps(e) for e in dict_sample.values()])
print(y)
  • Related