Xodarap777 Xodarap777 - 22 days ago 7
Python Question

Adding values or adding new tuples in Python

I have a list of tuples such as:

tuplist = [('New York', 546), ('Chicago', 675)]


And new tuples to either add to the list or sum, according to the [0] index:

tup3 = ('New York', 655)
tup4 = ('Los Angeles', 1273)


To get:

[('New York', 1201), ('Chicago', 675), ('Los Angeles', 1273)]


I'm creating these lists as growing values in a dict as I loop through a CSV. So if the above represents
{'Apples': [(City1, Number1), (City2, Number2)]}
, I currently use:

if fruit not in city_fruitd:
city_fruitd[fruit] = [(city, count)]
else:
city_fruitd[fruit] += [(city, count)]


How do I instead check for existing cities and sum accordingly if the city already exists?

Answer

You want to check for the case where the city is in the list of cities:

city in [x[0] for x in city_fruitd[fruit]]

Then find this city index

index = [city_fruitd[fruit].index(x) for x in city_fruitd[fruit] if city == x[0]][0]

And assign it the added value

city_fruitd[fruit][index] = [(city, city_fruitd[fruit][index][1] + count)]

So:

if fruit not in city_fruitd:
    city_fruitd[fruit] = [(city, count)]
elif city in [x[0] for x in city_fruitd[fruit]]:
    index = [city_fruitd[fruit].index(x) for x in city_fruitd[fruit] if city == x[0]][0]
    city_fruitd[fruit][index] = [(city, city_fruitd[fruit][index][1] + count)]
else:
    city_fruitd[fruit] += [(city, count)]