Python-Dictionary Basic Usage

Keywords: Python Ruby

Dictionaries

The dictionary refers to
1. How to access and modify information in a dictionary.
2. How to traverse the data in a dictionary,
3. A list of dictionaries to store, a dictionary to store lists, and a dictionary to store dictionaries.

A dictionary is a series of key-value pairs that can be used to access the values associated with them.
The values associated with the keys can be numbers, strings, lists, or even dictionaries.In fact, any Python object can be used as a dictionary value.

1. Basic operations

1. Access dictionary values

Specify the dictionary name in turn and the keys enclosed in square brackets.

alien_0={'color':'green','points':5}
new_points=alien_0['points']
print('You just earned ' + str(new_points) + ' points!')
You just earned 5 points!

2. Add key-value pairs

alien_0={'color':'green','points':5}
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

Key-value pairs are arranged in a different order than they are added.

3. Create an empty dictionary first

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

Create an empty dictionary to store user-supplied data or when writing code that automatically generates a large number of key-value pairs.

4. Modify dictionary values

Modify the value of a dictionary by specifying the dictionary name, the key enclosed in square brackets, and the new value associated with the key in turn.

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

5. Delete key-value pairs

For unwanted information in a dictionary, you can use the **del()** statement to completely remove the corresponding key-value pairs.
When using the del statement, you must specify the dictionary name and the key to delete.

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

6. Dictionaries of similar objects

favorite_languages = {    'jen':'python',    'sarah':'c',    'edward':'ruby',    'phil':'python'    }   
print("Sarah's favorite language is " +    favorite_languages['sarah'].title() +    ".")
Sarah's favorite language is C.

2. Traversing through a dictionary

The ways to traverse a dictionary are to traverse all key-value pairs, keys, or values in the dictionary.

1. Traverse through all key-value pairsDict.items()

dict.items() Returns a list of all key-value pairs in the dictionary.

favorite_languages = {    'jen':'python',    'sarah':'c',    'edward':'ruby',    'phil':'python'    }   
print(favorite_languages.items())
for name,language in favorite_languages.items():
    print(name.title() + "'s favorite language is " + language.title() + ".") 
dict_items([('jen', 'python'), ('sarah', 'c'), ('edward', 'ruby'), ('phil', 'python')])
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Ruby.
Phil's favorite language is Python.

When traversing a dictionary, the order in which key-value pairs are returned is not necessarily the same as the order in which they are stored.

2. Traverse all keys of a dictionaryDict.keys()

Extract all keys of a dictionary:dict.keys(), returns a list containing all the keys of the dictionary.

favorite_languages = {    'jen':'python',    'sarah':'c',    'edward':'ruby',    'phil':'python'    }   
print(favorite_languages.keys())
#for name in favorite_languages.keys():
for name in favorite_languages:    
    print(name.title()) 
dict_keys(['jen', 'sarah', 'edward', 'phil'])
Jen
Sarah
Edward
Phil

When traversing a dictionary, all keys are traversed by default.
So for name in favorite_of the above codeLanguages.keys(): Replace with for name inFavorite.languages:, the output will not change.

3. Traverse all keys in the dictionary in order

Dictionaries always explicitly record associations between keys and values, but the order in which the elements of a dictionary are retrieved is unpredictable.

To return elements in a specific order, one way is to sort the returned keys in the for loop.
You can use sorted() to get a copy of a list of keys in a specific order.

favorite_languages = {    'jen':'python',    'sarah':'c',    'edward':'ruby',    'phil':'python'    }   
for name in sorted(favorite_languages.keys()):
    print(name.title() + ",thank you for taking the poll.") 
Edward,thank you for taking the poll.
Jen,thank you for taking the poll.
Phil,thank you for taking the poll.
Sarah,thank you for taking the poll.

4. Traverse through all values in the dictionaryDict.values()

It returns a list of values without any keys.

favorite_languages = {    'jen':'python',    'sarah':'c',    'edward':'ruby',    'phil':'python'    }   
for language in set(favorite_languages.values()):
    print(language.title()) 
C
Python
Ruby

To eliminate duplicates, use the collection set.
Calling set() on a list containing duplicate elements returns a new list that allows Python to find unique elements.

3. Nesting

Storing a series of dictionaries in a list or a list as a value in a dictionary is called nesting.

1. Dictionary List

aliens=[]
for alien_number in range(0,30):
    new_alien={'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien)
for alien in aliens[0:3]:
    if alien['color'] == 'green':
            alien['color'] = 'yellow'        
            alien['speed'] = 'medium'       
            alien['points'] = '10'   
for alien in aliens[:5]:
    print(alien)
print("......") 
{'color': 'yellow', 'points': '10', 'speed': 'medium'}
{'color': 'yellow', 'points': '10', 'speed': 'medium'}
{'color': 'yellow', 'points': '10', 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
......

aliens is a list of 30 alien dictionaries.

2. Store lists in dictionaries

The value of the dictionary is a list.
Whenever you need to associate a key to multiple values in a dictionary, you can nest a list in the dictionary.

favorite_languages = {'jen':['python','ruby'],'sarah':['c'],'edward':['ruby','go'],'phil':['python','haskell']}   
for name,languages in favorite_languages.items():
    print(name.title() + "'s favorite languages are:")
        for language in languages:        
            print('\t' + language.title())
Jen's favorite languages are:
        Python
        Ruby
Sarah's favorite languages are:
        C
Edward's favorite languages are:
        Ruby
        Go
Phil's favorite languages are:
        Python
        Haskell

The variable languages stores, in turn, each value in the dictionary, which is a list.

3. Store dictionaries in dictionaries

The value of a dictionary is a dictionary.

users={    
'aeinstein':{'first':'albert','last':'einstein','location':'princeton'},
'mcurie':{'first':'marie','last':'curie','location':'paris'}
}
for username,user_info in users.items():
    print('Username: ' + username.title())
    full_name=user_info['first'] + " " + user_info['last']    
    location=user_info['location']
    print('\tFull name: ' + full_name.title())    print('\tLocation: ' + location.title())
Username: Aeinstein
        Full name: Albert Einstein
        Location: Princeton
Username: Mcurie
        Full name: Marie Curie
        Location: Paris

The structure of the dictionary representing each user is the same.

Posted by andreea115 on Fri, 26 Jun 2020 17:49:21 -0700