字典操作

Posted shenjianping

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典操作相关的知识,希望对你有一定的参考价值。

一、字典基础

1、创建字典

一个字典通过一对大括号进行创建,键值之间使用(:)进行分隔,每一对键值之间使用(,)分隔,如果大括号中无值那么就是空字典;它是Python中唯一具有映射关系的数据类型,效率高于列表。

 d = "name":"bright",12:["jskfj",23]  #键唯一且为不可变数据类型

当然如果键值不唯一,也不会抛出异常,只不过相同的键会被覆盖掉。

d = "name":"bright",12:["jskfj",23],"name":"gh"  #键唯一且为不可变数据类型
print(d)

#-----------------------------------------输出———————————————
12: [jskfj, 23], name: gh

 2、dict函数

可以使用dict函数通过其它映射进行字典的创建

items=[(name,张三),[iphone,1872563541]]
d=dict(items)
print(d) #‘name‘: ‘张三‘, ‘iphone‘: 1872563541

可以看出,为dict函数传入一个列表,而列表的元素就是一个个的列表或者元组,元素中包含两个值,第一个值表示了字典的键,第二个值表示字典的值。

另外dict也可以通过关键字传参,创建字典。

d=dict(name=张三,iphone=1872563541)
print(d) #‘iphone‘: 1872563541, ‘name‘: ‘张三‘

如果dict函数不指定任何参数,就会创建一个空字典

d=dict()
print(d)#

二、字典的基本操作

1、len(dict)

返回字典中元素(键值对)的个数

d = "name":"bright",12:["jskfj",23],"name":"gh"
print(len(d))#2

2、dict[key]

#获取键对应的值
d = "name":"bright",12:["jskfj",23],"name":"gh"
result=d["name"]
print(result)#gh

#对键进行赋值
d = "name":"bright",12:["jskfj",23],"name":"gh"
d["name"]="root"
print(d)#12: [‘jskfj‘, 23], ‘name‘: ‘root‘

 3、del dict[key]

d = "name":"bright",12:["jskfj",23],"name":"gh"
del d["name"]
print(d)#12: [‘jskfj‘, 23]

4、key in dict

判断dict中是否含有键为key的项

d = "name":"bright",12:["jskfj",23],"name":"gh"
print("name" in d)#True

5、字典格式化字符串

在字符串的格式化中,已经有很多方法了,这里也可以通过字典进行格式化,引进format_map()方法。

定义格式化参数字典:

data=
    "name":"bright",
    "age":27,
    "hobby":"music"

定义字符串模板:

str="""

name is a boy,age years old,liking hobby.

"""

使用format_map()方法格式化字符串:

print(str.format_map(data))#bright is a boy,27 years old,liking music.

6、序列与迭代

(1)获取字典中的key

d = "name":"bright",12:["jskfj",23],"name":"gh"
for key in d:
    print(key)
######输出######
    12
    name

(2)获取字典中的key和value

d = "name":"bright",12:["jskfj",23],"name":"gh"
for key,val in d.items():
    print(key,val)
    
#########输出######
    12 [jskfj, 23]
    name gh

 (3)并行迭代

同时迭代多个序列,可以使用range函数获取索引的范围,然后使用for循环进行迭代,注意多个序列一般元素个数相同。

schools=[beida,fudan,shifan]
citys=[北京,上海,天津]
for  i in range(len(schools)):
    print(schools[i],citys[i])
##########输出########
    beida 北京
    fudan 上海
    shifan 天津

(4)压缩序列

 使用zip函数将两个或多个序列的对应元素做为一个元组放到一起,如果压缩的两个或多个序列元素个数不相等,以元素个数最少的为准。

schools=[beida,fudan,shifan]
citys=[北京,上海,天津]
print(zip(schools,citys))
print(type(zip(schools,citys)))
for i in zip(schools,citys):
    print(i)
############输出###########
    <zip object at 0x0000000005220D08>
    <class zip>
    (beida, 北京)
    (fudan, 上海)
    (shifan, 天津)

(5)反转序列迭代

通过reversed函数对一个序列进行反转

citys=[北京,上海,天津]
result=reversed(citys)
print(result)
for i in result:
    print(i)
###########输出##########
    <list_reverseiterator object at 0x00000000054657B8>
    天津
    上海
    北京

7、其它

  • 键类型

字典的键可以是任意不可变类型,例如,元组、字符串等,而列表的key也就是index必须是整数类型。

  • 自动添加

字典可以通过dict[key]=value进行添加新元素,而列表必须通过append()或insert()方法进行添加新元素。

  • key in dict

字典中查找的仅仅是字典的key,而列表中查找的是value,而非index.

 三、字典方法

技术图片
class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object‘s
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = 
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """
    def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass

    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. """
        pass

    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. """
        pass

    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D‘s items """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D‘s keys """
        pass

    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
        """
        pass

    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

    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 """
        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]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D‘s values """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ True if D has a key k, else False. """
        pass

    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object‘s
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = 
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None
dict类

1、clear()

清空字典中的所有元素

d = "name":"bright",12:["jskfj",23],"name":"gh"
d.clear()
print(d)#

2、copy()与deepcopy()

copy()方法复制的字典只是浅复制,复制的是第一层的字典数据。也就是说修改原字典还是新字典,对应的元素都会改变。

d = "name":"bright",12:["jskfj",23]
d1=d.copy()
print(d1)
print(d)

############输出###########################
    12: [jskfj, 23], name: bright
    12: [jskfj, 23], name: bright

修改原字典中的值:

d = "name":"bright",12:["jskfj",23]
d1=d.copy()
d["name"]="alb"
print(d1)
print(d)

#################输出################
    12: [jskfj, 23], name: bright
    12: [jskfj, 23], name: alb

修改copy后新字典中的值:

d = "name":"bright",12:["jskfj",23]
d1=d.copy()
d1["name"]="sjp"
print(d1)
print(d)

###############输出###################
12: [jskfj, 23], name: sjp
12: [jskfj, 23], name: bright

修改第二层数据:

d = "name":"bright",12:["jskfj",23]
d1=d.copy()
d[12][0]=56
print(d)
print(d1)

################输出###############
12: [56, 23], name: bright
12: [56, 23], name: bright

从上面可以看到修改第二层数据,无论是修改新字典还是原字典,另外一个字典的值都会改变,如果想改变这种情况,就需要进行深拷贝。

from copy import deepcopy
d = "name":"bright",12:["jskfj",23]
d1=deepcopy(d)
d[12][0]=78
print(d)
print(d1)
###################输出##################
    12: [78, 23], name: bright
    12: [jskfj, 23], name: bright

3、fromkeys()

用于根据key建立新的字典,该方法的返回值就是新的字典。在新的字典中所有的key都有相同的默认值None,不过可以根据fromkeys方法的第二个参数进行指定默认值。

#在新字典上调用fromkeys创建新的字典,通过列表指定key
dic=.fromkeys([name,age,hobby])
print(dic) #‘hobby‘: None, ‘age‘: None, ‘name‘: None

 #通过元组指定key
 dic=.fromkeys((‘name‘,‘age‘,‘hobby‘))
 print(dic) #‘hobby‘: None, ‘age‘: None, ‘name‘: None

通过fromkeys的第二个参数指定默认值

dic=.fromkeys((name,age,hobby),bx)
print(dic) #‘hobby‘: ‘bx‘, ‘age‘: ‘bx‘, ‘name‘: ‘bx‘

4、get()

获取对应key的value,使用dict[key]可以获取值,但是一旦key不存在就会抛出异常,get()方法就不会抛出异常,如果key不存在,会返回None值。当然也可以通过get的第二个参数指定传入的默认值。

d = "name":"bright",12:["jskfj",23]
print(d.get("name"))#bright
print(d.get("age"))#None

5、items()与keys()

在字典的基本操作中已经说明了这两种方法,items方法用于获取字典的key-value,返回值是一个可迭代的dict_items类型;keys方法用于返回字典中所有的key,是dict_keys类型,也是可迭代的。

d = "name":"bright",12:["jskfj",23]
result1=d.items()
result2=d.keys()
print(type(result1))
for key,val in result1:
    print(key,val)
print(type(d.keys()))
for key in result2:
    print(key)
    
#########输出############
<class dict_items>
12 [jskfj, 23]
name bright

<class dict_keys>
12
name

6、pop()和popitem()

pop方法和popitem方法用于弹出字典中的元素,pop方法用于获取指定的key的值,并从字典中弹出这个key-value,popitem方法用于返回最后一个key-value,并且弹出这对key-value。

#pop方法
dict=name:xiaoli,depart:xiaoshou,age:27 print(dict.pop(name))#xiaoli print(dict)#‘age‘: 27, ‘depart‘: ‘xiaoshou‘ #popitem方法 dict=name:xiaoli,depart:xiaoshou,age:27 print(dict.popitem())#(‘age‘, 27) print(dict)#‘name‘: ‘xiaoli‘, ‘depart‘: ‘xiaoshou‘

7、setdefault()

setdefault方法用于设置key的默认值,该方法接收两个参数,第一个表示key,第二个表示默认值,如果key在字典中不存在,那么就会向字典中添加key,并用第二个参数作为值(参数未指定就为None),如果字典中已经存在key,setdefault不会修改key原来的值,而且该方法会返回原来的值。

dict=
dict.setdefault("name","menb")
dict.setdefault("name","niko")
dict.setdefault("age")
print(dict)

##############输出########
age: None, name: menb

其实这个方法与dict[key]=value差不多,但是这个方法可以添加元素,但是不能修改元素,因为已经存在的key,它只会返回不会修改,而dict[key]=value既可以添加又可以修改。

8、update()

update方法用于一个字典中的元素更新另外一个字典。该方法接收一个参数,该参数表示用作更新数据的字典的数据源。列如:

d1.update(d2)

将d2中的元素更新到d1中,如果d2中的key-value对在d1中不存在,就会在d1中新添加key-value对,如果d2中的key在d1中已经存在,那么就会把d2中的key的value更新给d1中key的value。

d1="name":"bright","age":27,"hobby":"music"
d2="name":"sansha","city":"陕西"
d1.update(d2)
print(d1)#‘city‘: ‘陕西‘, ‘hobby‘: ‘music‘, ‘age‘: 27, ‘name‘: ‘sansha‘

9、values()

获取字典中的值,返回的是dict_values类型,是可迭代的。它与keys方法返回的有一点不一样就是,它返回的值得列表可以有重复的,而keys()方法返回的都是唯一值的列表。

dict="name":"bright","age":27,"hobby":"music"
result=dict.values()
print(type(result))
for val in result:
    print(val)
##########输出###########
    <class dict_values>
    music
    27
    bright

四、总结

对字典操作最多的无非就是增、删、查、改这些基本操作,现在就对这些基本操作总结一下。

 d = "name":"bright",12:["jskfj",23]

# #查
 print(d["name"])
 print(d.get("name",None)) #推荐

##增加
# d["age"] = "123"
# d.default("age","123")
 print(d)

#修改
# d["name"] = "zhangfei"

#删除
# ret = d.pop(12)
# del d[12]
# print(ret)

##更新
 d1 = "name":"alia",12:["jskfj",23]
 d2 =  "name":"megon",12:["jskfj",23],"age":32
 d2.update(d)
 print(d2)

 

以上是关于字典操作的主要内容,如果未能解决你的问题,请参考以下文章

Python代码阅读(第19篇):合并多个字典

Python代码阅读(第26篇):将列表映射成字典

Python代码阅读(第40篇):通过两个列表生成字典

VSCode自定义代码片段——git命令操作一个完整流程

VSCode自定义代码片段15——git命令操作一个完整流程

VSCode自定义代码片段15——git命令操作一个完整流程