Python12_ dictionary

Outline

Use key - value (key-value) is stored, having a fast search speed

key features:

  1. key must be unique
  2. The key must be immutable object (string, integer, etc. are immutable, as key, List is variable, not as a key, usually strings)
  3. A dictionary is unordered (in most languages, dictionaries are unordered)

Thoughts: Save more for the student's name and achievements

If List
`[[" Tome ", 93], [" Jack ", 45]]

Use the dictionary: student's name as a key, as the result value

dict1 = {"Tome":60,"lilei":70}

ps: dictionary can only key without value

Access elements

Obtain

Format: Name Dictionary [key], corresponding to the key to access the corresponding value. Without the key, the error

print(dict1["lilei"])   #输出70
  • get(key,defaultValue)

When we were not sure whether there is a key in the dictionary, but also to obtain its value, you can use the get ()

Common

Without the key, is not being given, return None

print(dict1.get("sunck"))
print(dict1.get("sunck","1234"))	#如果不存在sunck键,则返回1234,否则返回sunck的value

Add to

dict1["hanmeimei"] = 99

Update

Because a key corresponding to a value, so many times to assign a key value, the value was modified

dict1["lilei"] = 89

delete

pop(key)

There is also a list of pop, if the parameter is not specified, the last element is deleted

dict1.pop("Tome")

of the

  • Delete individual items
    Format: del dictionary name [key]

  • Delete the entire dictionary, the dictionary does not exist after you remove the whole
    format: del dictionary name

clear

clear the dictionary is empty, but dictionaries inherent

Format: Dictionary name .clear ()

Traversal

for key in dict1:
    print(key,dict1[key])   #遍历的是字典里面的key

for value in dict1.values(): #遍历字典里面的value。dict.values是将dict字典里面的所有value以列表的形式返回
    print(value)
    
for k,v in dict1.items():   #dict.items()是将字典里面的元素以元组的形式返回
    print(k,v)  #输出key以及对应的value
    
for i,k2 in enumerate(dict1):
    print(i,k2) #i为key在字典里面的序号(从0开始),k2为键值

Dictionary of common operations

The dictionary as a parameter

Only ()

Returns the number of key-value pairs in the dictionary of

Format: len (dictionary name)

The caller dictionary

keys()

Format: Dictionary name .keys ()

Get all of the dictionary keys, a list of the form

info = {"name":"lisi","age":23}
if "name" in info.keys():
	pass

values()

Format: Dictionary name .values ​​()

Get all the values ​​of the dictionary, a list of the form

items()

Format: Dictionary name .items ()

Back key stored in key-value tuples of the form as List

my_dic={"name":laoli,"age":34}
for tmp in my_dic.items():
	print(tmp)
	print("key1:%s\tkey2:%s"%(tmp[0],tmp[1]))

list VS. dict

dict

  1. Find and insertion of extremely fast, it will not increase the key-value and slow
  2. It takes a lot of memory, memory waste and more (because you want to store key)

list

  1. Find and insert the speed increase against the amount of data and slow down
  2. Small footprint, less memory is wasted

# Little practice

Look how many times appeared substr in str

#法一:count
str.count(substr)

#法二:字典

Word = input("请输入要查找的单词:\n)

str = "sunck is a good man, sunck is a great man, sunck is a handsome man, sunck is a noble man"

myDic = {}
for i in str.split(" "):    #以空格切割字符串,循环处理列表中的每个元素,再以元素当作key去字典中提取数据
    v = myDic.get(i)    #如果直接myDic[key],当字典中不存在值为key的键时,程序会报错,所以用get
    if v == None:   #如果没有提取到,就以该元素作为key,1作为value,存进字典
        myDic[i] = 1
    else:
        myDic[i] += 1   #如果提取到了,则将对应的value+1
print(myDic[Word])  #再以该key去字典提取value

Guess you like

Origin blog.csdn.net/qq_34873298/article/details/89575943
Recommended