conditional Append to dictionary if condition match
Question:
I have list of dictionary, I want conditional append to dictionary if object value is uppercase.
For example:
Input:
[{'object':'Apple','category':'Fruit'}, {'object':'cat', ‘category’:'Aquatic'},{'object':'FISH',’category’:'Animal'}]
Output:
[{'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.
Answers:
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()
print(data)
[{'object': 'Apple', 'category': 'Fruit', 'new_object': 'apple'}, {'object': 'cat', 'category': 'Aquatic'}, {'object': 'FISH', 'category': 'Animal'}]
I have list of dictionary, I want conditional append to dictionary if object value is uppercase.
For example:
Input:
[{'object':'Apple','category':'Fruit'}, {'object':'cat', ‘category’:'Aquatic'},{'object':'FISH',’category’:'Animal'}]
Output:
[{'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.
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()
print(data)
[{'object': 'Apple', 'category': 'Fruit', 'new_object': 'apple'}, {'object': 'cat', 'category': 'Aquatic'}, {'object': 'FISH', 'category': 'Animal'}]