Concat only values in list of dictionary

Question:

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?

Asked By: HG K

||

Answers:

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]
Answered By: Tim Roberts

simple and straight forward –

t = []
for i in range(len(a)):
    t.append(a[i]['class'] + "." + a[i]['number'])
Answered By: Dev

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']
Answered By: Shubham Jha
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.