python之字典
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之字典相关的知识,希望对你有一定的参考价值。
一、字典的定义
字典是python中唯一的映射类型。
二、字典类型与序列类型的区别:
1.存取和访问数据的方式不同。
2.序列类型只用数字类型的键(从序列的开始按数值顺序索引);
3.映射类型可以用其他对象类型作键(如:数字、字符串、元祖,一般用字符串作键),和序列类型的键不同,映射类型的键直4.接或间接地和存储数据值相关联。
5.映射类型中的数据是无序排列的。这和序列类型是不一样的,序列类型是以数值序排列的。
6.映射类型用键直接“映射”到值。
字典是Python中最强大的数据类型之一。
字典的声明方法(两种)
三、字典中的方法
def clear(self): # real signature unknown; restored from __doc__
"""
D.clear() -> None. Remove all items from D.
清空字典
"""
pass
eg:
def copy(self): # real signature unknown; restored from __doc__
"""
D.copy() -> a shallow copy of D
字典的浅拷贝
"""
pass
@staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
"""
Returns a new dict with keys from iterable and values equal to value.
创建并返回一个新字典,以seq中的元素做该字典的键,val做该字典中所有键对应的初始值(默认为None)
"""
pass
eg:
def get(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None)
"""
pass
eg:
def items(self): # real signature unknown; restored from __doc__
"""
D.items() -> a set-like object providing a view on D‘s items
返回一个包含所有(键,值)元祖的列表
"""
pass
eg:
def keys(self): # real signature unknown; restored from __doc__
"""
D.keys() -> a set-like object providing a view on D‘s keys
返回一个包含字典所有KEY的列表
"""
pass
eg:
def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
弹出指定key值的元素(因为字典是无序的,所以必须指定key值)
"""
pass
eg:
def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
随机弹出
"""
pass
eg:
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
但如果字典中不存在Key键,由 adict[key] = default 为它赋值
"""
pass
def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
键值对添加到字典adict中
"""
pass
eg:
def values(self): # real signature unknown; restored from __doc__
"""
D.values() -> an object providing a view on D‘s values
获取字典中的值
"""
pass
eg:
四、练习题
有如下值的集合【11,22,33,44,55,66,77,88,99,90】,将所有大于66的值保存至字典的第一个key中,将小于等于66的值保存至第二个key中,即{‘k1’:大于66,‘k2’:小于66}
方法一:
结果
方法二:
结果:
以上是关于python之字典的主要内容,如果未能解决你的问题,请参考以下文章