0
Q:

how to use dictionaries in python

# Empty Dictionary
dictionary = {}
# Populated Dictionary
dictionary = {'a': 1, 'b': 2, 'c': 3}
6
clear() - Removes all the elements from the dictionary
copy() - Returns a copy of the dictionary
fromkeys() - Returns a dictionary with the specified keys and value
get() - Returns the value of the specified key
items() - Returns a list containing a tuple for each key value pair
keys() - Returns a list containing the dictionary's keys
pop() - Removes the element with the specified key
popitem() - Removes the last inserted key-value pair
setdefault() - Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() - Updates the dictionary with the specified key-value pairs
values() - Returns a list of all the values in the dictionary
5
student_data = {
  "name":"inderpaal",
  "age":21,
  "course":['Bsc', 'Computer Science']
}

#the keys are the left hand side and the values are the right hand side
#to print data you do print(name_of_dictionary['key_name'])

print(student_data['name']) # will print 'inderpaal'
print(student_data['age']) # will print 21
print(student_data['course'])[0]
#this will print 'Bsc' since that field is an array and array[0] is 'Bsc'
3

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
3
thisdict = {
  "key1" : "value1"
  "key2" : "value2"
  "key3" : "value3"
  "key4" : "value4"
}
9
  new_player1 = { 'firstName': 'LaMarcus', 'lastName': 'Aldridge', 'jersey': '12', 'heightMeters': '2.11', 'nbaDebutYear': '2006', 'weightKilograms': '117.9'}
            new_player2 = { 'firstName': 'LeBron', 'lastName': 'James', 'jersey': '2', 'heightMeters': '2.03', 'nbaDebutYear': '2003', 'weightKilograms': '113.4' }
            new_player3 = { 'firstName': 'Kawhi', 'lastName': 'Leonard', 'jersey': '2', 'heightMeters': '2.01', 'nbaDebutYear': '2011', 'weightKilograms': '104.3' }  
  
  nba_players = []
  nba_players.append(player)
  nba_players.append(new_player1)
  nba_players.append(new_player2)
  nba_players.append(new_player3)
2
thisdictionary = {'key':'value','key1':'value1'}
print(thisdictionary['key'])
9

thisdict =	{

  "brand": "Ford",

  "model": "Mustang",

  "year": 1964

}

print(thisdict)

 
1

New to Communities?

Join the community