Dictionary of python data type‘

1. Why need dictionary type

>>> list1 = ["name", "age", "gender"]
>>> list2 = ["fentiao", 5, "male"]
>>> zip(list1, list2)

>>>userinfo=dict(zip(list1, list2))

// Combining the two lists through zip built-in functions
[('name', 'fentiao'), ('age', 5), ('gender', 'male')]
>>> list2[0]
// When programming directly, you can't understand that the first index represents the name.
'fentiao'
>>> list2[name]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
So dictionary is the only mapping type in python, key-value (hash table), dictionary object is changeable, but key must be changeable object.

2. Definition of dictionary

1. Define an empty dictionary

s = {}
print(type(s))

d = dict()
print(d, type(d))

2. Define dictionaries with elements

s = {
    'fentiao':[100, 80, 90],
    'westos':[100,100,100]
}
print(s, type(s))




d = dict(a=1, b=2)
print(d, type(d))

The key-value value value of a dictionary is called a key-value pair.

The key value must be an immutable object.

value values can be of any data type: int,float,long, complex, list, tuple,set, dict

3. Built-in method: fromkeys
The key in the dictionary has the same value value, defaulting to None

Example: 100 card numbers were randomly generated. The format of the card numbers was 610 334455 001 - 610 334455 100, and the initial passwords were 666666 66.

cards = []
for cardId in range(100):
    card = "610 334455 %.3d" %(cardId+1)
    cards.append(card)
print(cards)

print({}.fromkeys(cards))
print({}.fromkeys(cards, '666666'))


4. Dictionary Nesting

students = {
    '13021001': {
        'name':'Zhang long',
        'age':18,
        'score':100
    },
    '13021003': {
        'name': 'Zhang',
        'age': 18,
        'score': 90
    }
}
print(students['13021003']['name'])

2. The Characteristics of Dictionaries

Because the dictionary is out of order, it does not support indexing, slicing, repetition, joining, and only member operators.

1. Member operator, default to determine whether the key value exists.

d = dict(a=1, b=2)
print('a' in d)
print(1 in d)

2. for loop: default traversal dictionary key value;

for i in d:
    print(i)

3. enumeration

for i,v in enumerate(d):
    print(i, '-----', v)

 

3. Common methods of dictionary

1. Remove the corresponding value in the dictionary (two methods)

1. Remove the value from the dictionary according to the key. (Note: If the key does not exist, the error will be reported.)

d = dict(a=1, b=2)
a = d['a']
print(a)

2). get() function, get the value of the corresponding key in the dictionary, if the key does not exist, take the default value None, if you need to specify the return value, pass the value.

If the key exists, take out the corresponding result

d = dict(a=1, b=2)
print(d.get('a'))
print(d.get('c'))

2. View keys and values

services = {
    'http':80,
    'mysql':3306
}

# Look at all the key values in the dictionary
print(services.keys())

# Look at all the value values in the dictionary
print(services.values())

# Look at all key-value values in the dictionary
print(services.items())

# ergodic
for k,v in services.items():                            
    print(k , '--->', v)

for k in services:
    print(k, '--->', services[k])


3. Increase in key-value

1.dict[key] = value

#Add or change key-value pairs

d = dict(a=1, b=2)
d['g'] = 10
d['a'] = 10
print(d)

2    dict.upate{}

# If the key value already exists, update the value value value;
# If the key value does not exist, add the key-value value value.

d = dict(a=1, b=2)
d.update({'a':4, 'f':1})
 print(d)

3.dict.setdefault()

 #If the key value already exists, do not modify it.
 #If the key value does not exist, add the key-value value value; by default, the value value is None   

d = dict(a=1, b=2)

d.setdefault('g', 10)()
print(d)

4. Deletion of dictionaries

1. Delete dictionary elements based on key values

dic.pop(key)

del dic['key']

2. Delete dictionary elements randomly and return (key,value)

dic.popitem()

3. Delete all elements in the dictionary

dic.clear()


4. Delete the dictionary itself

del dic

4. practice

1. Input a paragraph to find the number of times a word appears and output it in a dictionary.

1)

words=input("Please enter a sentence:")
li=words.split(' ')
print(li)
#word=dict{li}
word = ({}.fromkeys(li))

for word1 in word:
    #word = ({}.fromkeys(li))
    if word1 in word:
        word[word1]=1
    else:
        word[word1]+=1
print(word)

2)

from collections import Counter
from collections import defaultdict
s=input('s:')
li=s.split()
wordDict = defaultdict(int)
for word in li:
    wordDict[word]+=1
print(wordDict.items())

c=Counter(wordDict)
print(c.most_common())

2. List de-duplication

#1. Converting to a collection
li = [1, 2, 3, 4, 65, 1, 2, 3]
print(list(set(li)))

#2. The Way of Dictionary

li=[1,2,3,4,5,4,3,2,1]
print({}.fromkeys(li).keys())

3. Implementing switch statement indirectly

while True:
    grade=input("Please enter your level:")
    d={
        'A':"excellent",
        'B':"good",
        'C':"qualified"
    }

    print(d.get(grade,"Invalid results"))

 

 

 

 

 

Keywords: Programming Python MySQL

Added by Hooker on Mon, 20 May 2019 02:02:12 +0300