1

I have a list of dictionaries. How would I go about converting all dictionaries' values to lowercase, whenever possible?

One caveat is that values can be None's, as well as ints.

Here's an example for what I have:

list_of_dicts = [{'People': 3, 'Sport': None},{'People': 6, 'Sport': 'Football'} ]

Expected result (note the last value - Football - has been lowercased:

list_of_dicts = [{'People': 3, 'Sport': None},{'People': 6, 'Sport': 'football'} ]

The accepted solution below works great. However, if you want only values for specific keys modified, you can tack on a quick test like so:

list_of_dicts = [{'PeopleCount': 3, 'Sport': None},    {'PeopleCount': 6, 'Sport': 'Football'} ]

for d in list_of_dicts:
    for key in d.keys():
        if isinstance(d[key], str) and key in ('sport','zzz','Sport'): #test if this is the field we want to lowercase
            d[key] = d[key].lower()
print(list_of_dicts)
FlyingZebra1
  • 1,285
  • 1
  • 18
  • 28
  • You cannot directly change `key` values of a dictionary - https://stackoverflow.com/a/4411748/7841468 – shuberman Aug 23 '19 at 02:45
  • Basically you will have to delete and reassign new value, altering a key value is not an option here. – shuberman Aug 23 '19 at 02:46
  • 1
    `[{key:(val.lower() if isinstance(val,str) else val) for key,val in i.items()} for i in list_of_dicts]` – Onyambu Aug 23 '19 at 03:33

2 Answers2

1

A way is to iterate over dictionary item an lowercase where the content is a string

list_of_dicts = [
    {'People': 3, 'Sport': None},
    {'People': 6, 'Sport': 'Football'},
    {'People': 6, 'Foo': 'Bar'},
]

for d in list_of_dicts:
    for key in d.keys():
        if isinstance(d[key], str):
            d[key] = d[key].lower()

 print(list_of_dicts)
lcapra
  • 1,420
  • 16
  • 18
1

I'd approach this by building a new list and using dict comprehensions for cleanly making the new dictionary on the fly. Because you have some exceptions (not always a string), a simple function helps.

def clean_strings(v):
     if isinstance(v, str):
         return v.lower()
     return v

l = []
for d in list_of_dicts:
   l.append({k: clean_strings(v) for k, v in d.items()})

And sample output:

In: l
Out:
[{'People': 3, 'Sport': None},
 {'People': 6, 'Sport': 'football'}]
Bartek
  • 15,269
  • 2
  • 58
  • 65