
记得最早学习的时候,遇到不会的字都会把字典找出来查询一下,现在有了手机慢慢的字典就不太常用了。我们今天在python中要讲的字典和之前查文字的字典是两种东西,两者之间使用上没有关联,所以有些小伙伴可不要闹出笑话啦。今天小编就为大家带来合并字典的代码方法,接下来一起看看怎么做吧。
1.合并两个字典
下面的方法将用于合并两个字典。
1 2 3 4 5 6 7 8 9 10 | def merge_two_dicts(a, b):
c = a.copy() # make a copy of a
c.update(b) # modify keys and values of a with the ones from b
return c
a = { 'x' : 1, 'y' : 2}
b = { 'y' : 3, 'z' : 4}
print(merge_two_dicts(a, b))
# {'y': 3, 'x': 1, 'z': 4}
|
在 Python 3.5 或更高版本中,我们也可以用以下方式合并字典:
1 2 3 4 5 6 7 8 | def merge_dictionaries(a, b)
return {**a, **b}
a = { 'x' : 1, 'y' : 2}
b = { 'y' : 3, 'z' : 4}
print(merge_dictionaries(a, b))
# {'y': 3, 'x': 1, 'z': 4}
|
2.将两个列表转化为字典
如下方法将会把两个列表转化为单个字典。
1 2 3 4 5 6 7 8 | def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = [ "a" , "b" , "c" ]
values = [2, 3, 4]
print(to_dictionary(keys, values))
# {'a': 2, 'c': 4, 'b': 3}
|
通过本篇的学习我们知道字典是可以进行合并的,而且列表是可以转化为字典的,这就是关于字典的一些使用方法的代码,小伙伴们可以试着练习一下。更多Python学习指路:PyThon学习网教学中心。