python3 有关字典的一些用法

 元组转字典,当元组重复的时候,字典中只需把相同的keys值的values相加

如:res = (('a', 1), ('a', 2), ('c', 3), ('d', 4))

转为:{'a': 3, 'c': 3, 'd': 4}

    
    # 组成字典,若重复,则是values值相加

    res = (('a', 1), ('a', 2), ('c', 3), ('d', 4))
    adict = {}
    for i in range(0, len(res)):
        if res[i][0] in list(adict.keys()):
            adict[res[i][0]] = int(adict[res[i][0]]) + int(res[i][1])
        else:
            adict[res[i][0]] = int(res[i][1])
    print(adict)

结果:

{'c': 3, 'd': 4, 'a': 3}

两个列表转字典:

zip函数的用法:   http://www.runoob.com/python/python-func-zip.html

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

 

zip 语法:

zip([iterable, ...])

参数说明:

  • iterabl -- 一个或多个迭代器;

直接放一个例子: 

a = ['a', 'b', 'c']
b = [1, 2, 3]
print(list(zip(a, b)))
print(dict(zip(a, b)))

结果:
[('a', 1), ('b', 2), ('c', 3)]
{'a': 1, 'b': 2, 'c': 3}

 

两个字典的比较,求不同

pdf_dict = {'a': 1, 'b': 2, 'c': 3}
sql_dict = {'a': 1, 'b': 4, 'd': 7}
# 两个字典key值的并集
all_keys = pdf_dict.keys() | sql_dict.keys()
print('K', 'pdf', 'sql')
for k in all_keys:
    # 三个判断,
    # 1.若key两者都存在时 判断values值是否相等
    # 2.key分别存在时,另一个写‘无’
    # 3.须注意在其中可能有0的存在,   在这里0说明没有既是‘无’
    if k in sql_dict.keys() and k in pdf_dict.keys():
        if pdf_dict[k] == sql_dict[k]:
            continue
        print(k, pdf_dict[k], sql_dict[k])
    elif k in sql_dict and sql_dict[k] != 0:
        print(k, '无', sql_dict[k])
    elif pdf_dict[k] != 0:
        print(k, pdf_dict[k], '无')


# 结果:
K pdf sql
b 2 4
d 无 7
c 3 无

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值