Python----零零碎碎----实用技巧----0002

本文介绍了一种快速找出多个字典中的公共键的方法,并提供了三种不同的实现方式。此外,还介绍了如何在Python中使用OrderedDict来创建有序字典。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何快速找到多个字典中的公共键(key)

#随机选取3个
from random import randint, sample
sample('abcdefg',3)
#['a','f','a']
#随机选取任意个
s1 = sample('abcdefg',radint(3,6))
#['d', 'a', 'f', 'e']
#随机生成字典dict
s1 = {k:randint(2,6) for k in (sample('abcdefg',randint(3,6)))}
#{'a': 3, 'b': 4, 'c': 3, 'd': 2, 'e': 4, 'f': 3}
#字典解析
s2 = {k:randint(2,6) for k in (sample('abcdefg',randint(3,6)))}
s3 = {k:randint(2,6) for k in (sample('abcdefg',randint(3,6)))}
#方法一:
res = []
for k in s1:
    if k in s2 and k in s3:
        res.append(k)
#方法二:
k1 = s1.keys()
k2 = s2.keys()
k3 = s3.keys()
k1 and k2 and k3
#方法三:
#每一个的keys集合
map(dict.keys(),[s1,s2,s3])
#交集
reduce(lambda a,b:a and b, map(dict.keys(),[s1,s2,s3]))

如何让字典保持有序

Python中字典默认是不具有有序这样的性质的

使用collections.OrderdDict,以OrderedDict代替内置字典Dict,依次将选手成绩存入OrderedDict

from collections import OrderedDict
d = OrderedDict()
d['Jim']=(1,35)
d['Lop']=(2,37)
d['kiu']=(3,40)
for k in d:print(k)
#按顺序读入
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值