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?
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]
simple and straight forward –
t = []
for i in range(len(a)):
t.append(a[i]['class'] + "." + a[i]['number'])
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']
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?
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]
simple and straight forward –
t = []
for i in range(len(a)):
t.append(a[i]['class'] + "." + a[i]['number'])
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']