Pyhton dictionary

A, Python dictionary definitions

In python, the dictionary is a series of key - value pairs, each key is associated with a value, you can use the key to access the value associated with it. Associated with the key values ​​can be numbers, strings, lists, and even dictionaries. In fact, any value may be used as Python object dictionary.

In Python, with dictionaries in curly braces {} in the series of key - value representing

例:alien = {‘color’:‘green’,'points':5}

Key - value is the value of two associated, when the specified key, Python returns the value associated therewith, and separated by a colon between the key values, the key - between value pairs separated by commas in the dictionary Python value pairs can be, the simplest is only a dictionary key - - how many key-value pairs stored.

Second, the dictionary of common operations

1, access to the dictionary values

To get the value associated with a key, you can specify the name of the dictionary and turn on the key in square brackets

alien_0 = {'color':'green'}

print(alien_0['color'])

2, add key - value pairs

Dictionary is a dynamic structure, where at any time add key - value pairs. To add key - value pairs may be sequentially specified dictionary name, and key values ​​associated with brackets.

alien_0 = {'color':'green','points':5}

alien_0['x_position'] =0

alien_0['y_position']=25

print(alien_0)

3, the dictionary modification value

alien_0 = {'color':'green','points':5}
print(alien_0)
print("modify value:")
alien_0['color'] = 'yello'
print(alien_0)

4, delete key - value pairs

alien_0 = {'color':'green','points':5}

alien_0 = {'color':'green','points':5}
print(alien_0)
del alien_0['points']
print(alien_0)

5, traversing dictionary

1, through all the key - value pairs

user_0 = {
    'usernam': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
}

for key, value in user_0.items(): #user_0.items()返回的是一个键——值对列表
    print("\nkey" + key)
    print("\nvalue:" + value)

statement for the second part contains a dictionary name and method items (), which returns a key - value pair list, next, for each of the key turn loop - to the specified values ​​stored in two variables; note, even if the dictionary is traversed key - returns the value of the order different from the order stored. Python is not of keys - the storage sequence of value pairs, but only trace association between the keys and values.

6, traversing all the keys in the dictionary

When the value does not need to use the dictionary, the method keys () is useful

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in favorite_languages.keys():
    print(name.title())

6, all values ​​traversing dictionary

If only the value of the dictionary required, using values ​​() method returns a list of fat value not contain any key

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in favorite_languages.values():
    print(name.title())

In order to eliminate the use of a set of duplicate entries may be set, each element in the set must be unique

for name in set(favorite_languages.values()):
    print(name.title())

7, nesting

Sometimes, you need to be in the list, which is called a nested series of dictionaries stored in the dictionary can be nested list, you can also nest in the dictionary and even a list of dictionary nesting dictionary;

alien_0 = {'color':'green','points':5}
alien_1 = {'color':'yello','points':15}
alien_2 = {'color':'red','points':25}

aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)

7.1, in the list stored in the dictionary

pizza = {
    'crust':'thick',
    'toppings':['mushrooms','extra cheese']#嵌套的列表
}
for topping in pizza['toppings']:
    print("\t"+topping)

7.2, nested dictionaries in the dictionary

Applicable scene: If you have multiple user sites, each with a unique user name, user name can be in the dictionary as a key, and then in a dictionary, and the dictionary as the user name of each user's information is stored value associated with it.

users = {
    'aeinstenin': {
        'first': 'albert',
        'last': 'einstenin',
        'location': 'princetion',
    },
    'mcuire': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
    }
}

for username, user_info in users.items():
    print("\nUsername" + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    print("\tfull_name" + full_name)
    print("\tlocation" + location)

7.3, methods to remove elements of the dictionary

(1), pop (key [, default]: Deletes the specified key, and the key corresponding to the value returned

            d = {'a':1,'b':2,'c':3}

            Delete key value of 'a' element, and the value assigned to the variable E;

            e = d.pop('a')

            print (e)

            If the key does not exist, then the return value may be set

            e2 = d.pop('m','404')

            print(e2)

            If the key does not exist, does not set the return value error (error not to python3)

             e3 = d.pop('m')

(2)、del[d['key']]

            d = {'a':1,'b':2,'c':3}

            Remove the given key elements:

           the d [ 'a']

(3), popitem (): role in python3 popitem () method is to remove the last of the key and value pair in the dictionary, and the keys and values ​​return

        d = {'a':1,'b':2,'c':3,'d':5}
        c = d.popitem()
        print(c)

   

(4)、clear:一次性删除字典中的所有元素

                  d = {'a':1,'b':2,'c':3,'d':5}

                  print(d)

                  d.clear()

                  print(d)

发布了14 篇原创文章 · 获赞 1 · 访问量 279

Guess you like

Origin blog.csdn.net/weixin_38829588/article/details/104277228