码迷,mamicode.com
首页 > 其他好文 > 详细

字典生成式

时间:2019-10-22 09:12:07      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:for   href   class   logs   tle   res   com   code   key   

技术图片

[字典生成式]

一、字典生成式

print({i: i**2 for i in range(10)})
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

二、zip()方法

keys = ['name', 'age', 'gender']
values = ['nick', 19, 'male']

res = zip(keys, values)
print(F"zip(keys,values): {zip(keys,values)}")

info_dict = {k: v for k, v in res}
print(f"info_dict: {info_dict}")
zip(keys,values): <zip object at 0x11074c088>
info_dict: {'name': 'nick', 'age': 19, 'sex': 'male'}

通过解压缩函数生成一个字典

info_dict = {'name': 'nick', 'age': 19, 'gender': 'male'}
print(f"info_dict.keys(): {info_dict.keys()}")
print(f"info_dict.values(): {info_dict.values()}")

res = zip(info_dict.keys(), info_dict.values())
print(F"zip(keys,values): {zip(info_dict.keys(),info_dict.values())}")

info_dict = {k: v for k, v in res}
print(f"info_dict: {info_dict}")
info_dict.keys(): dict_keys(['name', 'age', 'gender'])
info_dict.values(): dict_values(['nick', 19, 'male'])
zip(keys,values): <zip object at 0x1105cefc8>
info_dict: {'name': 'nick', 'age': 19, 'gender': 'male'}

字典生成式

标签:for   href   class   logs   tle   res   com   code   key   

原文地址:https://www.cnblogs.com/leimingqq2/p/11717406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!