简体   繁体   English

Python - 将列表的字典值相乘并将结果存储回不同的字典中?

[英]Python - multiply dictionary values for a list and store the result back in a different dictionary?

I have this problem: two dictionaries, one "dicT" and the other "dictionary".我有这个问题:两个字典,一个“dict”和另一个“字典”。 I want to multiply "dicT" for a list (listT) and store the result back in a dictionary, with keys from dicT.我想将“dict”乘以列表(listT)并将结果存储回字典中,并使用来自 dict 的键。 Any ideas?有任何想法吗?

I thought to do the following:我想做到以下几点:

    for i in dPdT:
        for value in dicT.values():
            if not i in dictionary:
                dictionary[i] = []
            dictionary[i].append(i*value)

But it ends up in the following traceback message:但它最终出现在以下回溯消息中:

Traceback (most recent call last):
  File "isochore.py", line 197, in <module>
    main()
  File "isochore.py", line 164, in main
    dictionary[i].append(i*value)
TypeError: can't multiply sequence by non-int of type 'float'

Thanks!谢谢!

Could you give an example of the data and what you expect it to do?您能否举一个数据示例以及您期望它做什么? What do you expect when you multiply i * value while you think i is also a key so perhaps alphanumeric?当您将 i * 值相乘而您认为 i 也是一个键(可能是字母数字)时,您会期望什么? That is also the errorcode you are getting.这也是您得到的错误代码。

I tried to guess, please provide actual data because I don't understand what you are trying to do?我试图猜测,请提供实际数据,因为我不明白您要做什么? This is providing all the values in list l multiplied with that value of l so basically **2?这是提供列表 l 中的所有值乘以 l 的值,所以基本上是 **2?

oldDictionary = {1: 10,2: 20}
L =[0, 2]
newDictionary = {}

for i in L:
    if i in oldDictionary:
        newDictionary.update({i: oldDictionary.get(i) * i})

print(newDictionary)
{2: 40}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM