Home > Blockchain >  Concat only values in list of dictionary
Concat only values in list of dictionary

Time:08-25

I'd like to concat only values for list of dict.

Input :

a = [
    {'class': 'A', 'number': '1'}, 
    {'class': 'B', 'number': '2'},
    {'class': 'C', 'number': '3'},
]

Expected Output:

b = [
    'A.1',
    'B.2',
    'C.3'
] 

Is there 1 line statement for this?

CodePudding user response:

Sure:

b = [f"{k['class']}.{k['number']}" for k in a]

Or, if you like,

b = ['.'.join(k['class'],k['number']) for k in a]

CodePudding user response:

This code can do it easily and also ensure to join all the values of the dictionary.

[".".join(i.values()) for i in a]
# result:
['A.1', 'B.2', 'C.3']

CodePudding user response:

simple and straight forward -

t = []
for i in range(len(a)):
    t.append(a[i]['class']   "."   a[i]['number'])
  • Related