It's much easier to explain my doubts with an example:
I have a list with dictionaries of this type,
[
{
'portal_id': 5,
'url_imovel': 'asd.pt',
'url_photos': {0: 'pfoto1.pt', 1: 'pphoto2.pt'},
'total_photos': 2
},
{
'portal_id': 5,
'url_imovel': 'asd2.pt',
'url_photos': {0: 'pfoto12.pt', 1: 'pphoto22.pt'},
'total_photos': 2
},
{
'portal_id': 5,
'url_imovel': 'foo.pt',
'url_photos': {0: 'fotofoo1.pt', 1: 'photofoo2.pt', 1: 'photofoo3.pt'},
'total_photos': 3
}
]
The dictionary is generated as follows:
all_im_fotos = []
im_fotos = {
"portal_id" : 5,
"url_imovel" : str(),
"url_photos" : dict(),
"total_photos": int()
}
urls = "asd.pt"
photos_url = ["pfoto1.pt", "pphoto2.pt"]
im_fotos["url_imovel"] = urls
for i in range(len(photos_url)):
im_fotos["url_photos"].update({i: photos_url[i]})
im_fotos["total_photos"] = len(im_fotos["url_photos"])
all_im_fotos.append(im_fotos)
... same process ...
My question is, how can I compare the insertion of new values. My goal is to create a new dictionary that just insert new values, increasing the index of imfotos. For example:
difference = []
new_imovel = "asd.pt"
new_url_photos = ["pfoto1.pt", "pfoto3.pt"]
There is a new photo for the url "asd.pt", so we should add the difference by auto incrementing the index, resulting in:
[
{
'portal_id': 5,
'url_imovel': 'asd.pt',
'url_photos': {0: 'pfoto1.pt', 1: 'pphoto2.pt', 2: 'pfoto3.pt'},
'total_photos': 3
}
]
How can I make this as simple as possible? is it possible to save this dictionary as a json file in order to perform the same process later?
is it possible to save this dictionary as a json file in order to perform the same process later?
you can use json.dumps()
to convert python dict
to json, and use json.loads()
to read json file to python dict
.
datas = [
{
'portal_id': 5,
'url_imovel': 'asd.pt',
'url_photos': {0: 'pfoto1.pt', 1: 'pphoto2.pt'},
'total_photos': 2
},
{
'portal_id': 5,
'url_imovel': 'asd2.pt',
'url_photos': {0: 'pfoto12.pt', 1: 'pphoto22.pt'},
'total_photos': 2
},
{
'portal_id': 5,
'url_imovel': 'foo.pt',
'url_photos': {0: 'fotofoo1.pt', 1: 'photofoo2.pt', 2: 'photofoo3.pt'},
'total_photos': 3
}
]
new_imovel = "asd.pt"
new_url_photos = ["pfoto1.pt", "pfoto3.pt"]
for data in datas:
if data["url_imovel"] == new_imovel:
for photo in new_url_photos:
if not photo in data['url_photos'].values():
data['url_photos'].update({len(data['url_photos']):photo})
data['total_photos']+=1
print(datas)
[
{
"portal_id": 5,
"url_imovel": "asd.pt",
"url_photos": {0: "pfoto1.pt", 1: "pphoto2.pt", 2: "pfoto3.pt"},
"total_photos": 3,
},
{
"portal_id": 5,
"url_imovel": "asd2.pt",
"url_photos": {0: "pfoto12.pt", 1: "pphoto22.pt"},
"total_photos": 2,
},
{
"portal_id": 5,
"url_imovel": "foo.pt",
"url_photos": {0: "fotofoo1.pt", 1: "photofoo2.pt", 2: "photofoo3.pt"},
"total_photos": 3,
},
]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments