1

How to replace values from specific keys in listed dictionaries? But replace should happen with a conditional (i.e. if they have 2 digits in the beginning). Preferably with list/dictionary comprehensions.

Example:

a_list = [{'key1': 'A picture 1', 'key2': 'location 1', 'key3': '20 title1'}, {'key1': 'A picture 2', 'key2': 'location 2', 'key3': '10 title2'}]

I want to remove the first two digits from the values of key3.

3 Answers 3

1

I would do that using a dictionary comprehension within a list comprehension.

The dictionary comprehension rebuilds the dictionary, but alters the value if:

  • key is key3 AND
  • first 2 chars of the string are digits

Alteration is taking the right part of the leading space.

a_list = [{'key1': 'A picture 1', 'key2': 'location 1', 'key3': '20 title1'}, {'key1': 'A picture 2', 'key2': 'location 2', 'key3': '10 title2'}]

a_new_list = [{k:v.partition(" ")[2] if (k=="key3" and v[:2].isdigit()) else v for k,v in d.items()} for d in a_list]

print(a_new_list)

result:

[{'key1': 'A picture 1', 'key2': 'location 1', 'key3': 'title1'}, {'key1': 'A picture 2', 'key2': 'location 2', 'key3': 'title2'}]

Note: Will also remove the first digits if there are more than 2 digits. The condition is broad and should be tuned to your needs.

EDIT: a pre Python 2.7 compliant alternative (dict comprehensions when did not exist):

a_new_list = [dict((k,v.partition(" ")[2] if (k=="key3" and v[:2].isdigit()) else v) for k,v in d.items()) for d in a_list]
Sign up to request clarification or add additional context in comments.

3 Comments

That's great exactly what I was looking for. Thanks. I was thinking if we could do this with re.sub, but in any case I am going to adapt per my needs.
This works in python 2.7.X, however I am getting syntax error in python 2.6.X :(
that's because dict comprehensions were not available yet. edited for alternate solution, should work all right (gives the same results!!)
1

There may be a way to do this with comprehensions, but in my opinion it is better to be a little more verbose to make the code's intention more clear:

import re

for d in a_list:
    for k in d:
        d[k] = re.sub(r'^\d\d', '', d[k]) if k == 'key3' else d[k]

Comments

0

So I combined Jean-François Fabre's and Tom Lynch's answers, slightly altered regex patterned and came up with this:

import re

a_new_list = [{k: re.sub(r'^\d{2} ', '', d[k]) if k == "key3" else v for k, v in d.items()} for d in a_list]

print a_new_list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.