字典 - 用 _ 替换键的空格,保持值相同

Fly*_*ra1 2 python dictionary python-3.x

我有一个字典列表,其键包含空格。

input = [{'books author': 'bob', 'book title': 'three wolves'},{'books author': 'tim', 'book title': 'three apples'}]
Run Code Online (Sandbox Code Playgroud)

我将如何遍历上述字典列表,并用下划线替换包含空格的键,输出为

output = [{'books_author': 'bob', 'book_title': 'three wolves'},{'books_author': 'tim', 'book_title': 'three apples'}]
Run Code Online (Sandbox Code Playgroud)

请注意,实际字典可能包含数百个键,而一个列表将包含数千个dicts。

MrG*_*eek 5

您可以在dict-comprehension 中使用list-comprehension,并str.replace用于更改to _

in_list = [{'books author': 'bob', 'book title': 'three wolves'},{'books author': 'tim', 'book title': 'three apples'}]

out_list = [{k.replace(' ', '_') : v for k, v in d.items()} for d in in_list]

print(out_list)
Run Code Online (Sandbox Code Playgroud)

输出:

[{'books_author': 'bob', 'book_title': 'three wolves'}, {'books_author': 'tim', 'book_title': 'three apples'}]
Run Code Online (Sandbox Code Playgroud)