-3

how can merge the similar file's name together? for example, I have

{"Apple USA": 25$, "Apple Japan": 26$, "Avocado Mexico":30$, "Avocado Brazil":35$} 

then I want to know the total amount of cost of Apple and Avocado. how should I do that in Python?

And I want to have a table that shows

{"Apple":51$,"Avocado":65$}

Thank you!

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
dehua yue
  • 3
  • 1
  • does your data is like that way ? i mean is it in dict format ?If not then can you provide some data something like df.head() in question. – k33da_the_bug Feb 02 '21 at 15:02

2 Answers2

1

you can iterate the dict assumning that is a dict as you showed us...

from collections import defaultdict
data = {"Apple USA": 25, "Apple Japan": 26, "Avocado Mexico":30, "Avocado Brazil":35} 
dic = defaultdict(lambda: int(0))
for key,val in data.items():
    name,*_ = key.split()
    dic[name] = dic[name] + val

Output:

>>>dict(dic)

 {'Apple': 51, 'Avocado': 65}
adir abargil
  • 5,495
  • 3
  • 19
  • 29
0

You should iterate over the dictionary and use split() to separate the key into pieces.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222