[python]字典的一键多值
来源:互联网 发布:淘宝网宝贝详情模板 编辑:程序博客网 时间:2024/06/05 08:45
今天在写一个小代码的时候要用到这样的数据结构:一个由dict { key, list [ ] }组成的List列表。可是,如何实现呢?
查阅了《Python Cookbook》,有以下三种方式:
1. d1 = { }
d1.default ( key, [ ] ).append(value)//用List实现
2. d2 = { }
d2.setdefualt( key, { })[ value ] = 1//使用字典作为dict的值,自然而然的消灭了重复值的可能
3. d3 = { }
d3.setdefault ( key, set( ) ).add(value)//在python 2.4中
我采取了第一种的实现方式。
代码示例:
list_p = ['abc','efg','hij']all_list = []for i in list_p: s = {} s.setdefault(i,[1,2,3]) all_list.append(s) print all_list运行结果如下:
[{'abc': [1, 2, 3]}, {'efg': [1, 2, 3]}, {'hij': [1, 2, 3]}]
0 0
- [python]字典的一键多值
- <Python>字典,可爱的字典
- Python的字典操作
- Python的字典
- Python的字典操作
- python的{}字典操作
- python的字典
- Python的字典操作
- Python的字典操作
- Python的字典操作
- Python的字典操作
- Python字典的应用
- Python的字典相关
- python的字典学习
- Python的字典操作
- python的字典
- Python的字典排序
- Python 字典的排序
- 用live555将内网摄像机视频推送到外网服务器
- TiXmlDocument 解析 C++ vc xml元素文本修改
- 遥感数据下载地址
- TCP校验和计算原理与实现
- linux命令 gzip命令
- [python]字典的一键多值
- DSP-BIOS使用入门
- php 判断文件或目录是否存在
- 什么情况下可以不写PHP的结束标签“?>”
- Android AIDL使用详解
- 【爱上Java8】ACC_SUPER和早期的invokespecial
- LeetCode Longest Palindromic Substring
- Fiddler参数解读
- 第一个chrome应用