[英]Is there a way to combine common keys and add values in Python?
Hi there ive seen various posts on how to combine two dictionaries in Python, However what I would like to do is combine like keys in the same dictionary and add the values?嗨,我看到了关于如何在 Python 中组合两个字典的各种帖子,但是我想做的是在同一个字典中组合类似的键并添加值? ..in truth what i will do initially is rename the keys into various categories and then id like to combine similar keys and add the values.
..事实上,我最初要做的是将键重命名为各种类别,然后 id 喜欢组合相似的键并添加值。 is there a simple method to make this possible?
有没有一种简单的方法可以做到这一点? at the moment ive opted for iterating and changing keys..but this seems a slow way of doing things.
目前,我选择了迭代和更改键..但这似乎是一种缓慢的做事方式。 im wondering whether or not to iterate over transaction description first and create a new list then zip or not?
我想知道是否先迭代事务描述并创建一个新列表,然后再创建 zip? any ideas apprecaited thanks.
任何想法都非常感谢。
here is my modest start这是我谦虚的开始
df = pd.read_csv("spreadsheet.csv")
item = df['Transaction Description']
cost = df['Debit Amount']
purchases = {}
purchases = {}
key, value in zip(item, cost):
purchases[key] = value
keys = purchases.keys()
for i in purchaces.keys {
if key == "Soverign housing"
purchases [Rent] = purchaces[Soverign housing]
del dictionary[Soverign housing]
...etc
The simplest is to use in
to see if a new dictionary contains a key from each dictionary, in this example i used *args
which is the list of the arguments to make it more flexible.最简单的方法是使用
in
查看新字典是否包含每个字典中的键,在此示例中,我使用了*args
,它是 arguments 的列表,以使其更加灵活。
dic_a = {'A': 20, 'B': 30, 'C': 40}
dic_b = {'A': 5, 'C': 2, 'F': 100}
dic_c = {'H': 32, 'K': 75, 'G': 15}
def combine_dict(*args):
comb = dict()
for dic in args:
for key in dic:
if key in comb:
comb[key] += dic[key]
else:
comb[key] = dic[key]
return comb
if __name__ == '__main__':
print(combine_dict(dic_a, dic_b))
print(combine_dict(dic_a, dic_b, dic_c))
I don't understand what does your mean about condensed values etc.我不明白您对浓缩值等的含义是什么。
@user1717828 is Right for asking input/Out code so we can understand it clearly. @user1717828 适合询问输入/输出代码,因此我们可以清楚地理解它。
But how much i understand is that you want when you combine 2 dict object it should keep same keys but combine Values eg但是我理解的是,当您结合 2 dict object 时,您想要它应该保留相同的键但结合值,例如
dict_a = {'A':1, 'B': 2, 'C':3}
dict_b = {'A':10, 'C': 20, 'D':30}
for key,val in dict_b:
try:
_key = dict_a[key] # Already Exist Key in Dict A
except: # If Object does not Exist
dict_a[key]=val
else: # If exist Then Make a list and Append
dict_a_val = dict_a[key] #Current value in dict_a
dict_a[key] = []
dict_a[key].append(dict_a_val)
dict_a[key].append(val)
#output:
# {'A':[1,10], 'B': 2, 'C':[3,20] , 'D':30}
Hope you were looking for this希望你在找这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.