I have to update the list of dictionaries, more precisely: if the value is greater than 70 then the value associated then the key should be uppercase, otherwise if it is less than or equal to 70 it should be lowercase. I tried to use a for loop but I get this error for k,v in list():
TypeError: 'list' object is not callable
This is what I have so far:
list = [{'brand':'nokia', "age":"56"}, {'brand':'motorola', "age":"80"}, {'brand':'sony', "age":"42"}, {'brand':'allview', "age":"10"}, {'brand':'huawei', "age":"15"}]
for k,v in list():
if v > 50:
list[k].upper()
else:
list[k].lower()
print = list()
CodePudding user response:
Given your code, I made the following solution
list = [{'brand':'nokia', "age":"56"}, {'brand':'motorola', "age":"80"}, {'brand':'sony', "age":"42"}, {'brand':'allview', "age":"10"}, {'brand':'huawei', "age":"15"}]
#set the range n for index 0,n to the number of dictionary entries in your list.
for index in range(0,5):
print(list[index]["age"])
# if list([index]["age"])>70:
# print("old asF")
int_value = int(list[index]["age"])
if int_value >70:
new_key = "Age"
old_key = "age"
#using the .pop method we assign a new key where we removed the age key.
list[index][new_key] = list[index].pop(old_key)
print(list)
gives the following output
[{'brand': 'nokia', 'age': '56'}, {'brand': 'motorola', 'Age': '80'}, {'brand': 'sony', 'age': '42'}, {'brand': 'allview', 'age': '10'}, {'brand': 'huawei', 'age': '15'}]
CodePudding user response:
what you want maybe:
s = [{'brand':'nokia', "age":"56"}, {'brand':'motorola', "age":"80"}, {'brand':'sony', "age":"42"}, {'brand':'allview', "age":"10"}, {'brand':'huawei', "age":"15"}]
[ {'brand': item['brand'], 'AGE' if int(item['age']) > 70 else 'age': item['age']} for item in s]
the output is:
[{'brand': 'nokia', 'age': '56'}, {'brand': 'motorola', 'AGE': '80'}, {'brand': 'sony', 'age': '42'}, {'brand': 'allview', 'age': '10'}, {'brand': 'huawei', 'age': '15'}]
