You are on page 1of 9

DICTIONARY IN PYTHON

A dictionary is an unordered set of key: value pairs. It provides us with a way to


map pieces of data to each other so that we can quickly find values that are
associated with one another.
 A dictionary begins and ends with curly braces { and }.
 Each item consists of a key ("avocado toast") and a value (6). Which is
separated by :
 Each key: value pair is separated by a comma.
 It’s considered good practice to insert a space () after each comma, but our
code will still run without the space.
 We can have a list or a dictionary as a value of an item in a dictionary, but
we cannot use these data types as keys of the dictionary. If we try to, we
will get a Type error.
 An empty dictionary can be defined as { }

 To add a single key: value pair to a dictionary, we can use the syntax:
Dictionar_name [key] = value
Example : sensors = {"living room": 21, "kitchen": 23, "bedroom": 20,
"pantry" : 22}

To add single pair,


sensors[“Bathroom”] = 10

 If we wanted to add multiple key: value pairs to a dictionary at once, we


can use the .update() method.
Example : sensors = {"living room": 21, "kitchen": 23, "bedroom": 20,
"pantry" : 22}

To add multiply strings:


sensors.update({"pantry": 22, "guest room": 25, "patio": 34})
 To overwrite values in a dictionary we simply use the existing key and
change the value using the following syntax.

To overwrite single pair, the previous value was 10


sensors[“Bathroom”] = 25
# now it is overwritten to 25.

 Combining two lists: Let’s say we have two lists that we want to combine
into a dictionary, like a list of students and a list of their heights, in inches:

Example:
names = ['Jenny', 'Alexus', 'Sam', 'Grace']
heights = [61, 70, 67, 64]

Python allows you to create a dictionary using a dict. comprehension, with


this syntax:

students = {key:value for key, value in zip(names, heights)}


#students is now {'Jenny': 61, 'Alexus': 70, 'Sam': 67, 'Grace': 64
USING DICTIONARIES IN PYTHON

1. TO GET VALUE FROM A KEY:


Once you have a dictionary, you can access the values in it by providing
the key.
Using the following syntax :

value_of_key = name_of_dictionary[name_of_key]

If the key is not in the dictionary it will generate a key error, to avoid
this error we can use

( I ) The ‘if’ condition:

caffeine_level = {"espresso": 64, "chai": 40, "decaf": 0, "drip": 120}

example: if expresso = “espresso”

If expresso in caffeine_level:
print(caffeine[“expresso”])

( II ) Use try/except :

caffeine_level["matcha"] = 30
try:
print(caffeine_level["matcha"])
except KeyError:
print("Unknown Caffeine Level")

The safest way to get the value of the key:


Dictionaries have a .get() method to search for a value instead of the
my_dict[key] notation we have been using. If the key you are trying to
.get() does not exist, it will return None by default:

Inside the parenthesis of .get, we write the name of the key of which
value we want to fetch.

In the .get ( ) method we can also set a default value of a key if the key is
not found in the dictionary.

For example, if we are going to fetch the value of “Dave age” and we don’t know if
Dave’s age is present in the data or not, we can give the user “ Dave age’s not
found”

X = data_employee.get(“Dave age”, “Age not found”)


#it will return Dave’s age if present and if not present it will print the not found
message and will be stored in x.

2. TO DELETE A KEY :

.pop() works to delete items from a dictionary when you know the key
value.

X = data_employee.pop(“Dave age”, “Age not found”)


#it will return Dave’s age if present and if not present it will print the not found
message and will be stored in x and also delete the dave age key.

.pop( ) can store also store the value of the key in the variable but it will
delete the key permanently from the dictionary.

If you do not know that a key exists that you are going to pop out you
can present or store a default value to variable.
3. GET ALL THE KEYS OUT OF THE DICTIONARY :

Dictionaries also have a .keys() method that returns a dict_keys object.

A dict_keys object is a view object, which provides a look at the current


state of the dictionary, without the user being able to modify anything.

The dict_keys object returned by .keys() is a set of the keys in the


dictionary. You cannot add or remove elements from a dict_keys object,
but it can be used in the place of a list for iteration:

for student in test_scores.keys(): # This command has all keys of dict.


print(student) # print all keys

4. GET ALL VALUES OUT OF THE DICTIONARY:

Dictionaries have a .values() method that returns a dict_values object


(just like a dict_keys object but for values!) with all of the values in the
dictionary.

It can be used in the place of a list for iteration

5. GET ALL ITEMS OUT OF THE DICTIONARY:

You can get both the keys and the values with the .items() method.
Like .keys() and .values(), it returns a dict_list object. Each element of
the dict_list returned by .items() is a tuple consisting of: (key, value)
(tuple = values of tuples can not be changed by any means)

Syntax : dict_name.items( )
It will convert a dictionary into a list with each key:value as a list item
Another Example :

biggest_brands = {"Apple": 184, "Google": 141.7, "Microsoft": 80, "Coca-Cola":


69.7, "Amazon": 64.8}

for company, value in biggest_brands.items():


print(company + " has a value of " + str(value) + " billion dollars. ")
HOW TO APPEND SOMETHING IN DICTIONARY VALUES WITHOUT REPLACING
OR POPING:

Consider you have a dictionary as follows:


my_dict = {"Name":[],"Address":[],"Age":[]};

The keys in the dictionary are Name, Address, and Age. Using append() method
can update the values for the keys in the dictionary.

my_dict = {"Name":[],"Address":[],"Age":[]};

my_dict["Name"].append("Guru")
my_dict["Address"].append("Mumbai")
my_dict["Age"].append(30)
print(my_dict) = {'Name': ['Guru'], 'Address': ['Mumbai'], 'Age': [30]}
Scrabble Solution :

letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", 
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 
8, 4, 10]

letters_to_points = {key:value for key,value in zip(letters,points)}

letters_to_points[" "] = 0

def score_word(word):
  word = word.upper()
  score = 0
  for char in word:
    if char in letters_to_points:
      score += letters_to_points[char]
  return score

#print(score_word("brownie"))

player_to_words = {'Blue':["Earth","Eraser","Zap"],"Tennis":
["Eyes","Belly","Coma"],"Exit":["Machine","Husky","Period"]}

def play_word(player,word):
   player_to_words[player].append(word)
   return player_to_words

play_word('Blue',"Cricket")
play_word("Tennis","Zoology")
play_word("Exit","Kangaroo")
play_word('Blue',"Pokimon")
play_word('Tennis',"Cristanio Ronaldo")
play_word("Exit","Lional Messi ")
play_word("Blue","Zoopathology")
print(player_to_words)

players_to_points = {}

for players,words in player_to_words.items():
  player_points = 0
  for word in words:
    player_points += score_word(word)
  players_to_points[players]= player_points
print(players_to_points)
      

You might also like