lundi 26 juillet 2021

How to add or delete a missing key value from one list to another

I've been working with lists o better understand them. I came across this idea of having two lists that have similar keys and values. List one has a dictionary that has a key state: city with two values, while list two has one of the values missing. On the other hand, list two has an extra value from one of the dictionary keys state: city not on list one. For the first piece of code, I want to update list two with the missing value from list one. For the second piece of code, I want to remove the extra value from list two that is missing on list one This is what I have for the moment.

list_one = [
    {
        'name': 'California',
        'state': [{'id': '34567', 'city': 'LA'}, {'id': '67890', 'city': 'San Francisco'}],
        'region': 'W'
    },
    {
        'name': 'Texas',
        'state': [{'id': '45678', 'city': 'Austin'}],
        'region': 'SW'
    },
    {
        'name': 'New York',
        'state': [{'id': '56789', 'city': 'Brooklyn'}],
        'region': 'E'
    }
]

list_two = [
    {
        'name': 'California',
        'state': [{'id': '12345', 'city': 'Miami'}],
        'region': 'W'
    },
    {
        'name': 'Texas',
        'state': [{'id': '23456', 'city': 'Austin'}, {'id': '78901', 'city': 'Houston'}],
        'region': 'E'
    },
    {
        'name': 'New York',
        'state': [{'id': '01234', 'city': 'Brooklyn'}],
        'region': 'E'
    }
]


#update - if  list_one has cities not in list_two, add those
for state1 in list_one:
    for state2 in list_two:
        for city1 in state1['state']:
            for city2 in state2['state']:
                if city1['city'] not in city2['city']:
                    res = [i['state'] for i in list_one if i not in list_two]
                    if city1['city'] not in city2['city']:
                        city2['city'] = city1['city']

                #delete - if list_one doesn't have the city in list_two, delete it from 
                #list_two
                elif city2['city'] not in city1['city']:
                    old_city2 = city2
                    res = [i['state'] for i in list_one if i not in list_two]
                    res2 = [i['state'] for i in list_two if i not in list_one]
                    # city2['city'].remove()

I feel I'm doing a bit too much and it might be simpler. As for the id, I don't want to update them only the cities. If I need to delete a `city then I would like to remove that whole dictionary element.

Thank you!

Aucun commentaire:

Enregistrer un commentaire