I have below array:
object['table.column_values'] =
[
{'name1': '10.1.10.1', 'name2': '100~200', 'name3': ''},
{'name1': '2.2.2.2', 'name2': '', 'name3': '>1024'},
{'name1': '1.1.1.1', 'name2': '', 'name3': 'nam3'}
]
I want to add the word column-
to all keys like below:
[
{'column-name1': '10.1.10.1', 'column-name2': '100~200', 'column-name3': ''},
{'column-name1': '2.2.2.2', 'column-name2': '', 'column-name3': '>1024'},
{'column-name1': '1.1.1.1', 'column-name2': '', 'column-name3': 'nam3'}
]
for that, I use this algorithm:
for value_count in range(len(object['table.column_values'])):
for item in object['table.column_values'][value_count]:
edited_item = 'column-' item
row_values[edited_item] = object['table.column_values'][value_count][item]
all_values.append(row_values)
but it gives me an array with duplicated objects of last object:
[
{'column-name1': '1.1.1.1', 'column-name2': '', 'column-name3': 'nam3'},
{'column-name1': '1.1.1.1', 'column-name2': '', 'column-name3': 'nam3'},
{'column-name1': '1.1.1.1', 'column-name2': '', 'column-name3': 'nam3'}
]
Is there a way in python to handle this problem?
CodePudding user response:
You can use a nested list/dictionary comprehension to add column-
to all the key names:
result = [ { f'column-{k}' : v for k, v in d.items() } for d in object['table.column_values'] ]
Output:
[
{'column-name1': '10.1.10.1', 'column-name2': '100~200', 'column-name3': ''},
{'column-name1': '2.2.2.2', 'column-name2': '', 'column-name3': '>1024'},
{'column-name1': '1.1.1.1', 'column-name2': '', 'column-name3': 'nam3'}
]
CodePudding user response:
You can use list comprehension:
data = [
{'name1': '10.1.10.1', 'name2': '100~200', 'name3': ''},
{'name1': '2.2.2.2', 'name2': '', 'name3': '>1024'},
{'name1': '1.1.1.1', 'name2': '', 'name3': 'nam3'}
]
new_data = [{"column-" key: value for key, value in dic.items()} for dic in data]
print()