2017-02-14 77 views
0

我想创建一个新字典,它是原始字典的修改。以下是示例代码。乘整数字典

alex = { 
    'salary' = 50 
    'money' = 40 
    'saving' = 60 
    'debt' = 20 
} 

    crisis = 2 

    #where newalex is the result of alex * crisis 

newalex = { 
    'salary' = 100 
    'money' = 80 
    'saving' = 120 
    'debt' = 40 
} 

我该如何去做这件事?

回答

3

你可以借助字典理解做到这一点:

newalex = {key: value * crisis for key, value in alex.items()} 
#    ^^^^^^^^^^^^^^---- this multiplies every value with "crisis". 
+0

,并有可能改变危机的另一个字典,用独特的价值在亚历克斯的每个值相乘,通过他们的钥匙挂? –

+0

是的,你只需将它改为'newalex = {key:value * crisis [key] for key,value in alex.items()}'(假设'crisis'是一个与'alex'具有相同键的字典) 。 – MSeifert

+0

非常感谢!非常有帮助 –

0

这是python2.7

newalex = {} 
crisis = 2 
for key, val in alex.iteritems() 
    newalex[key] = val * crisis 

这是python3.4

newalex = {} 
crisis = 2 
for key, val in alex.items() 
    newalex[key] = val * crisis 
0

尝试是这样的使用dictionary comprehension

>>> alex = {'salary': 50, 'money': 40, 'saving': 60, 'debt': 20} 
>>> crisis = 2 
>>> new_alex = {k:v*crisis for k, v in alex.items()} 
>>> print(new_alex) 
{'money': 80, 'salary': 100, 'saving': 120, 'debt': 40} 
2

,你可以继承字典:

>>> class muldict(dict): 
... def __mul__(self, integer): 
... return muldict([[key, self[key] * integer] for key in self]) 
... 
>>> alex = muldict({'salary': 50, 'money': 40, 'saving': 60, 'debt': 20}) 
>>> alex * 2 
{'salary': 100, 'money': 80, 'debt': 40, 'saving': 120} 
2

大约有这两种方式,(我知道:P)

首先...

你,需要一个功能字典作为参数,

创建一个新的字典,

迭代在旧字典上;取值,将该值乘以一个因子,

然后您将返回新的字典。

或者...

而不是创建新字典,做对即是在函数解析的本地词典一样opperations。

这里是我的例子...

def mult_dictionary_new(dictionary,x): 
    new = {} 
    for key in dictionary: 
     new[key] = dictionary[key] * x 
    return new 

和替代的解决方案......

def mult_dictionary_modify(dictionary,x): 
    for key in dictionary: 
     dictionary[key] *= x 
    return dictionary 

编辑2:

进一步moar!

如果要将字典乘以另一个字典,请像这样更改函数。

def mult_dictionary(a,b): 
    for key in b: 
     a[key] *= b[key] 
    return a 

只要'b'是'a'的元素,这将工作。即'b'中的每个键都是'a'中的键。

末编辑2

希望这有助于:d

康纳

编辑1:我建议你使用,因为如果你正在寻找做各种各样的字典批量操作功能,这将是很容易。

确保一行解决方案可能是您需要的,但让您的程序具有有意义名称的功能对于故障排除来说是一个巨大的优势。

加...

确保你创建你的字典是这样的...

dict = {'key': value, 
     'another key': anothervalue} 

的,而不是...

dict = {'key' = value} 

键使用冒号分配':'不等于'=',词典中的每个元素都需要用逗号分隔','

您还可以通过执行指定键的值...

dict['key'] = value 
+0

毫无疑问:D,总是很乐意帮忙。 如果您在任何时候遇到任何其他的Python问题,或只是一般查询,请随时给我发电子邮件:[email protected] –