I have a dictionary were the "ID" represents the main structure identifier. Basically what I want to do is to loop through it, find if one of the values inside each of the ID's is in the correct format, and if not, remove the entire object.
Here is the structure of my dictionary:
As you can see, "id" is the main key of each object. In my case I'm trying to see if the sub-key "prezzo" is int he correct format.
Correct "prezzo": "100000" <--- Just an integer Wrong "prezzo": "da 100000 - 100000" char, spaces and double numbers. In this case I wanted to remove completely the object connected to the id, so in on 25 id's, number 3, 7 and 15 have the "prezzo" value wrong, they will be popped out of the dictionary...
I'm trying different solution, but ultimately am still not good enough with dictionaries, any suggestions on how to filter it out?
Thanks and have a lovely day!
CodePudding user response:
Maybe this minimal example helps. It basically tries to convert each value of the key prezzo
to an integer. If possible it will be added to the resulting dictionary. As you see also a floating point number is not a valid entry.
Find infos on dictionaries in python here.
dic={0:{'id':1,'prezzo':'da 30000 - 70000'},
1:{'id':12,'prezzo':'10000'},
2:{'id':17,'prezzo':'da 10000 - 12000'},
3:{'id':25,'prezzo':'7.5'}}
result_dic ={}
for k,v in dic.items():
try:
int(v['prezzo'])
result_dic[k]=v
except ValueError:
pass
print(result_dic)
Output:
{1: {'id': 12, 'prezzo': '10000'}}
CodePudding user response:
original_dicts = [{"id":1,"prezzo":"da 165000 - 25400"},
{"id":2,"prezzo":"da 290000 - 320000"},
{"id":3,"prezzo":"150000"},
{"id":4,"prezzo":"10000"}]
formated_dicts=[]
unformated_dicts=[]
for pos in range(len(original_dicts)):
#checking for id
if original_dicts[pos]["id"] and "id" in original_dicts[pos].keys():
try:
#taking prezzo integer type only
int(original_dicts[pos]["prezzo"])
formated_dicts.append(original_dicts[pos])
except:
unformated_dicts.append(original_dicts[pos])
else:
print('some of dictionaries dont have "id"')
print(formated_dicts)
print(unformated_dicts)
Output:
[{'prezzo': '150000', 'id': 3}, {'prezzo': '10000', 'id': 4}]
[{'prezzo': 'da 165000 - 25400', 'id': 1}, {'prezzo': 'da 290000 - 320000', 'id': 2}]