2

I have a list of dictionaries whose keys contain spaces.

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

How would I go about iterating over the said list of dictionaries, and replacing the keys' that contain spaces, with underscores, with output being

output = [{'books_author': 'bob', 'book_title': 'three wolves'},{'books_author': 'tim', 'book_title': 'three apples'}]

Note, the actual dictionaries can contain a few hundred keys, and a list will consist of thousands of dicts.

martineau
  • 119,623
  • 25
  • 170
  • 301
FlyingZebra1
  • 1,285
  • 1
  • 18
  • 28
  • What have you tried so far, and what went wrong with your attempts? – G. Anderson Aug 30 '19 at 18:31
  • I understand where you're coming from . Basically I tried iterating over the list of dicts, using .items() in py 3, then generating brand new dictionaries... which i figured is probably the least efficient way of doing it: x = [{'books author': 'bob', 'book title': 'three wolves'},{'books author': 'tim', 'book title': 'three apples'}] import copy y = [] for oned in x: for key,value in oned.items(): print(key,value) oned[key] = key.replace(" ","_") print(key) print(oned) – FlyingZebra1 Aug 30 '19 at 18:40

2 Answers2

5

You can use a dict-comprehension within a list-comprehension, and use str.replace for the changing of 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)

Output:

[{'books_author': 'bob', 'book_title': 'three wolves'}, {'books_author': 'tim', 'book_title': 'three apples'}]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
2

A mix of list comprehension a dict comprehension could work:

res = [{(k.replace(" ", "_")):v for (k,v) in dct.items()} for dct in inp]
developer_hatch
  • 15,898
  • 3
  • 42
  • 75