Here’s a sample of the data:
JavaScript
x
11
11
1
[{
2
'name': 'Age',
3
'p_value': '<0.001',
4
'ks_score': '0.07',
5
},
6
{
7
'name': 'peer_LM_Mean_SelfAware',
8
'p_value': '<0.001',
9
'ks_score': '0.06',
10
}]
11
I have over 16k dictionaries with several items in the list. What I want to do is replace the value of name
in this dictionary from another dictionary which consists of the old name and new name.
JavaScript
1
9
1
col_rename_list = {'Male': 'Male, n (%)',
2
'Age': 'Age, years',
3
'Baby_Boomers__1946_1964_': 'Baby Boomers (1946-1964), n (%)',
4
'Generation_X__1965_1980_': 'Generation X (1965-1980), n (%)',
5
'Generation_Y___Millennials__1981_1996_': 'Generation Y/Millennials (1981-1996), n (%)',
6
'Race_Asian': 'Asian, n (%)',
7
'peer_LM_Mean_SelfAware': 'Self-Awareness'
8
}
9
How can I do this? One way that I could think of is the following:
JavaScript
1
6
1
for d in dictionary_list:
2
for k,v in d.items():
3
if k == 'name':
4
if col_rename_list.get(v) is not None:
5
d[k] = col_rename_list.get(v)
6
This works, but is there a better and efficient way to do this?
Advertisement
Answer
You can use dict.get
with with default parameter:
JavaScript
1
30
30
1
lst = [
2
{
3
"name": "Age",
4
"p_value": "<0.001",
5
"ks_score": "0.07",
6
},
7
{
8
"name": "peer_LM_Mean_SelfAware",
9
"p_value": "<0.001",
10
"ks_score": "0.06",
11
},
12
]
13
14
col_rename_list = {
15
"Male": "Male, n (%)",
16
"Age": "Age, years",
17
"Baby_Boomers__1946_1964_": "Baby Boomers (1946-1964), n (%)",
18
"Generation_X__1965_1980_": "Generation X (1965-1980), n (%)",
19
"Generation_Y___Millennials__1981_1996_": "Generation Y/Millennials (1981-1996), n (%)",
20
"Race_Asian": "Asian, n (%)",
21
"peer_LM_Mean_SelfAware": "Self-Awareness",
22
}
23
24
for d in lst:
25
d["name"] = col_rename_list.get(d["name"], d["name"])
26
27
# pretty print:
28
from pprint import pprint
29
pprint(lst)
30
Prints:
JavaScript
1
3
1
[{'ks_score': '0.07', 'name': 'Age, years', 'p_value': '<0.001'},
2
{'ks_score': '0.06', 'name': 'Self-Awareness', 'p_value': '<0.001'}]
3