Skip to main content

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

python basics-6 dictionary

6 dictionary

6.1 Create a simple dictionary

    # Creating a Simple Dictionary
alien_0 = {'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.2 Using dictionaries

A dictionary is a collection of key-value pairs, using "keys" to access the values ​​associated with them. Values ​​associated with keys can be numbers, strings, lists, or even dictionaries

6.2.1 Accessing values ​​in a dictionary

    # Accessing values in a dictionary
alien_0 = {'color':'green'}
print(alien_0['color'])

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.2.2 Adding key-value pairs

    # Adding Key-Value Pairs
alien_0 = {'color':'green','points':5}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary
6.2.3 First create an empty dictionary

    # First create an empty dictionary
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.2.4 Modify values ​​in the dictionary

    # Modifying values in a dictionary
alien_0 = {'color':'green'}
print(alien_0['color'])

alien_0['color'] = 'yellow'
print(alien_0['color'])

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

    alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
print('Original x-position:' + str(alien_0['x_position']))

if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print('New x-postion:' + str(alien_0['x_position']))

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.2.5 Delete key-value pairs

Use del to delete key-value pairs

    # Deleting key-value pairs
alien_0 = {'color':'green','points':5}
print(alien_0)

del alien_0['points']
print(alien_0)

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.2.6 Dictionaries composed of similar objects

Dictionaries can also store the same information for multiple objects

    # Dictionaries can also be used to store the same information for multiple objects
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print("sarah's favorite languages is " +
favorite_languages['sarah'].title() +
".")

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.3 Traversing the dictionary

Use the for statement and the method items()
to declare any two variables to store the keys and values ​​​​in the dictionary key-value pairs.

    # Iterate over all key-value pairs in the dictionary
user_0 ={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key,value in user_0.items(): # Declare key and value variables to store the key and value in a key-value pair.
print('\nKey:' + key)
print('value:' + value)

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

    # Iterate over all key-value pairs in the dictionary
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name,language in favorite_languages.items(): # The name and language are declared here.
print(name.title() + "'s favorite languages is " +
language.title() +".")

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.3.2 Iterate over all keys in the dictionary

The method key() can be implemented or omitted, but it will be easier to understand if it is displayed

    # Iterate over all keys in the dictionary
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in favorite_languages.keys(): # The key() could be omitted here, but it's easier to understand when written this way
print(name.title())

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

    # Iterate over all keys in the dictionary
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
friends = ['phil','sarah'] # The following actions are performed when the specified name is met
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi" + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

    # Iterate over all keys in the dictionary
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
if 'erin' not in favorite_languages.keys():
print("Erin,please take our poll!")

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.3.3 Traverse all keys in the dictionary in order

    # Iterate over all keys in the dictionary
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.")

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.3.4 Iterate over all values ​​in the dictionary

The method values() can be implemented

    # Iterate over all values in the dictionary
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print('The following languages have been mentioned:')
for language in favorite_languages.values():
print(language.title())

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

Use set() to extract unique values

    # Iterate over all the values in the dictionary and extract the non-repeating languages with set().
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print('The following languages have been mentioned:')
for language in set(favorite_languages.values()): # Extract non-repeating languages via set()
print(language.title())

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

6.4 Nesting
6.4.1 Dictionary list

    # Nested, Dictionary List
alien_0 = {'color':'green', 'points':5}
alien_1 = {'color':'yellow', 'points':10}
alien_2 = {'color':'red', 'points':15}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

Use nesting to create 30 aliens

    # Nest, create 30 green aliens aliens=[] # Create an empty list of stored aliens

for alien_number in range(30): # create 30 green aliens new_alien = {'color':'green', 'points':5, 'speed':'slow'} aliens.append(new_alien)

for alien in aliens[:5]: # show first 5 aliens print(alien) print('...')

print('Total number of aliens:' + str(len(aliens))) # show how many aliens were created

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

Create 30 aliens and adjust them

    # Nest, create 30 green aliens and adjust aliens=[] # Create an empty list of stored aliens

for alien_number in range(30): # create 30 green aliens new_alien = {'color':'green', 'points':5, 'speed':'slow'} aliens.append(new_alien)

for alien in aliens[:3]: # Adjust the attributes of the first 3 green aliens to the attributes of the yellow alien if alien['color'] == 'green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points '] = 10

for alien in aliens[:5]: # show first 5 aliens print(alien) print('...')

print('Total number of aliens:' + str(len(aliens))) # show how many aliens were created

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary
6.4.2 Storing lists in dictionaries

    # Nesting, storing lists in dictionaries
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}

print('You ordered a' + pizza['crust'] + '-crust pizza' +
'with the following toppings:')

for topping in pizza['toppings']:
print('\t' + topping)

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary

    # Nesting, storing lists in dictionaries
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name, languages in favorite_languages.items():
print('\n' + name.title() + "'s favorite languages are:")
for language in languages:
print('\t' + language.title())

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary
6.4.3 Storing dictionaries within dictionaries

    # Nesting, storing dictionaries within dictionaries
users = {
'aeinstein':{
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie':{
'first': 'marie',
'last':'curit',
'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.title())
print('\tLocation: ' + location.title())

For self-study--Python basics--Excerpted from Python programming from entry to practice--6 dictionary