I have a list of dictionaries
list1 = [{'time': '2020', 'name': 'one', 'address': '15423'},{'time': '2021', 'name': 'two', 'address': '8548305'}, {'time': '2019', 'name': 'five', 'address': '15423'}]
I want to convert anything that has address with 15423 to 'Valid' and all the other cases Invalid Final output
list1 = [{'time': '2020', 'name': 'one', 'address': 'Valid'},{'time': '2021', 'name': 'two', 'address': 'Invalid'}, {'time': '2019', 'name': 'five', 'address': 'Valid'}]
Here is what I tried
if '15423' in list1['address']:
list1['address'] = 'Valid'
else:
list1['address'] = 'Invalid'
But I am not sure why it is not working. Maybe I need to loop through the whole column. Appreciate your help
CodePudding user response:
You need to iterate over the elements of list1
using a for
loop, since list1
is a list of dictionaries:
for i in range(len(list1)):
if '15423' in list1[i]['address']:
list1[i]['address'] = 'Valid'
else:
list1[i]['address'] = 'Invalid'
print(list1)
You can also condense the if/else
into a ternary if you're looking for a more concise solution:
for i in range(len(list1)):
list1[i]['address'] = 'Valid' if '15423' in list1[i]['address'] else 'Invalid'
Both of these print:
[{'time': '2020', 'name': 'one', 'address': 'Valid'},
{'time': '2021', 'name': 'two', 'address': 'Invalid'},
{'time': '2019', 'name': 'five', 'address': 'Valid'}]
CodePudding user response:
you have to loop through the list!
Why?
let's say num_list = [0, 1, 2, 3]
using a for
loop like so:
for item in num_list:
...
will loop through num_list
as you'd expect. item
will be set to the current value, in this case, it will set item
to 1
, do the code in the loop, then set item
to 2
, then do the code in the loop again, and so on.
now let's say num_list = [{"number": 0}, {"number": 1}, {"number": 2}, {"number": 3}]
.
this time, if you run the same for
loop, item
will still be set to the current value, in this case, it will set it to the dictionary instead of the number. thus, item
is set to {"number": 0}
, then the code inside the loop will run, then item
is set to {"number": 1}
, then the code inside the loop will run again, etc.
thus, item
will be set to a dictionary, which by then you can edit like any other dictionary! simply do item["number"] = ...
for the actual fixed code, here ya go
list1 = [
{'time': '2020', 'name': 'one', 'address': '15423'},
{'time': '2021', 'name': 'two', 'address': '8548305'},
{'time': '2019', 'name': 'five', 'address': '15423'}
]
for item in list1:
if item["address"] == "15423":
item["address"] = "Valid"
else:
item["address"] = "Invalid"
print(list1)
output:
[
{'time': '2020', 'name': 'one', 'address': 'Valid'},
{'time': '2021', 'name': 'two', 'address': 'Invalid'},
{'time': '2019', 'name': 'five', 'address': 'Valid'}
]