conditional Append to dictionary if condition match


I have list of dictionary, I want conditional append to dictionary if object value is uppercase.
For example:


[{'object':'Apple','category':'Fruit'}, {'object':'cat', ‘category’:'Aquatic'},{'object':'FISH',’category’:'Animal'}]


[{'object' : 'Apple','new_object' : 'apple','category':'fruit'},{'object' : 'cat',’category’ : 'aquatic'},{'object' : 'FISH','new_object' : 'fish',’category’ : 'animal'}]

Description: ‘Apple; and ‘FISH’ are in uppercase, so in output additional key, value need to append. If lowercase then no changes.

How can I achieve this, I have tried for loop and dict comprehension but not able to proceed further. Any leads pls.

Asked By: Pikun95



You can use a for loop to iterate over each dictionary in the list, and check if the value of the ‘object’ key has the first character uppercase using the istitle() method and check if it is fully capitalized using the isupper() method. If it is triggers either of the methods before, then you can append a new key-value pair to the dictionary with the lowercase version of the ‘object’ value.

data = [{'object': 'Apple', 'category': 'Fruit'}, {'object': 'cat',
                                                   'category': 'Aquatic'}, {'object': 'FISH', 'category': 'Animal'}]

for d in data:
    if d['object'].istitle() or d['object'].isupper():
        d['new_object'] = d['object'].lower()

[{'object': 'Apple', 'category': 'Fruit', 'new_object': 'apple'}, {'object': 'cat', 'category': 'Aquatic'}, {'object': 'FISH', 'category': 'Animal'}]
Answered By: Anonymous
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.