惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
B
Blog RSS Feed
阮一峰的网络日志
阮一峰的网络日志
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Help Net Security
MyScale Blog
MyScale Blog
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
Vercel News
Vercel News
S
SegmentFault 最新的问题
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
G
Google Developers Blog
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
云风的 BLOG
云风的 BLOG

博客园 - ayao

记录一次PVE(Proxmox VE)虚拟机从thin lvm 迁移到 ceph存储的问题 在PVE中实现宿主机与虚拟机同网段通信的配置方案 记一次stc单片机c51编程的指针问题 TrueNAS(原FreeNAS)的SMB共享文件夹,配置为不同的登录账户显示不同的目录 简要记录一下:ds1302 读取秒寄存器,总是在第一次读出ff,第二次才能读出准确的值的问题 使用单片机驱动74CH595(8位串行输入、并行输出、可级联芯片)遇到的问题和解决过程 解决pl2303在 windows 10 或windows 11 显示“PL2303HXA自2012已停产,请联系供货商”问题 安装libjpeg,让php支持jpeg图片的裁切、缩放等操作 如何从oracle官方网站下载旧版本的jdk jre 【转帖】通过PHP读取dbf数据(visual fox pro,VFP数据库),官方的dbase无法读取字段为类型memo的数据,国外网站的解决方案 How to read FoxPro Memo with PHP? 问题处理:php json_decode函数处理的字符串中含有反斜杠“\”时,处理出错,返回的结果为NULL - ayao - 博客园 keepalived绑定的ip一段时间(大约几分钟)后消失的问题 设置jquery-ui datepicker的z-index值 配置完成vsftp,无法上传文件和建立文件夹 解决方法 Nginx 负载平衡 支持域名转发的方法 设置网页的图标 C# 线程、timer例句 c# delegate应用一例,类似于javascript中直接写的回调函数 flexigrid js表格控件在IE7下内容显示为空白
python学习笔记——字典推导式
ayao · 2025-04-15 · via 博客园 - ayao

python学习 笔记——字典推导式

字典推导式,可以简化字典使用。字典:dict,键值对,值可修改,如{"a":"val1","key2":abc};元组,tuple,值集合,不可修改,省内存,如 g = ('abc',123,True);array,数组

# 使用字典推导式简化代码 
if cursor.description is None: 
    return {} 
return {item[0]: idx for idx, item in enumerate(my_dict)}
    my_dict = {'na':'tom','age':18,'sex':True}
    for idx, item in enumerate(my_dict):
        print(f"idx:{idx}, item:{item}")

输出:这里是取键的元组进行便利,item类型是str
idx:0, item:na
idx:1, item:age
idx:2, item:sex  

  my_dict = {'na':'tom','age':18,'sex':True}
    for k, v in my_dict:
        print(f"k:{k}, v:{v}")
结果:报错如图。这种遍历方式,只能获得值,获取不到键

    my_dict = {'na':'tom','age':18,'sex':True}
    for k, v in my_dict.items():
        print(f"k:{k}, v:{v}")
输出:
k:na, v:tom
k:age, v:18
k:sex, v:True

========================================
    my_dict = {'na':'tom','age':18,'sex':True}
    for k in my_dict.keys():
        # print(f"k:{k}, v:{v}")
        print(f"{k}")
输出:
na
age
sex

==========================================
    my_dict = {'na': 'tom', 'age': 18, 'sex': True}
    dict1 = {item:idx for idx,item in enumerate(my_dict)} #字典
    dict2   = {k:v for k,v in my_dict.items()}            #字典
    arr1 = [f"{k}:{v}" for k,v in enumerate(my_dict)]     #数组
    arr2 = [f"{k}:{v}" for k,v in my_dict.items()]        #数组
    tuple1 = (1,2,True,"str",my_dict)                     #元组
    tuple2 = (f"{k}:{v}" for k,v in my_dict.items())      #元组

    print("dict1:\n",dict1)
    print("dict2:\n",dict2)
    print("arr1:\n",arr1, '\njoin to str:',','.join(arr1))
    print("arr2:\n",arr2, '\njoin to str:',",".join(arr2))
    print(tuple1)
    print("tuple1:\n",tuple1)
    print('join to str:',",".join(tuple2)) #join正确,元素必须为str类型
    print('join to str:',",".join(tuple1)) #join出错,元素必须为str类型,才能join;其他类型报错


输出:

dict1:
 {'na': 0, 'age': 1, 'sex': 2}
dict2:
 {'na': 'tom', 'age': 18, 'sex': True}
arr1:
 ['0:na', '1:age', '2:sex'] 
join to str: 0:na,1:age,2:sex
arr2:
 ['na:tom', 'age:18', 'sex:True'] 
join to str: na:tom,age:18,sex:True
(1, 2, True, 'str', {'na': 'tom', 'age': 18, 'sex': True})
tuple1:
 (1, 2, True, 'str', {'na': 'tom', 'age': 18, 'sex': True})
join to str: na:tom,age:18,sex:True
Traceback (most recent call last):
  File "D:\work\coding\gas_data_process\test.py", line 19, in <module>
    print('join to str:',",".join(tuple1)) #join出错,元素必须为str类型,才能join;其他类型报错
                         ~~~~~~~~^^^^^^^^
TypeError: sequence item 0: expected str instance, int found