Answers for "python dictionary methods"

95

python dictionary

#Creating dictionaries
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}

#Creating new pairs and updating old ones
dict1['area'] = 25 #{'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
dict2['perimeter'] = 20 #{'color': 'red', 'edges': 4, 'perimeter': 20}

#Accessing values through keys
print(dict1['shape'])

#You can also use get, which doesn't cause an exception when the key is not found
dict1.get('false_key') #returns None
dict1.get('false_key', "key not found") #returns the custom message that you wrote 

#Deleting pairs
dict1.pop('volume')

#Merging two dictionaries
dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
dict1 #{'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}

#Getting only the values, keys or both (can be used in loops)
dict1.values() #dict_values(['red', 'square', 25, 4, 20])
dict1.keys() #dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
dict1.items() 
#dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])
Posted by: Guest on May-20-2020
32

python dictionary

#title			:Dictionary Example
#author         :Josh Cogburn
#date           :20191127
#github         :https://github.com/josh-cogburn
#====================================================

thisdict = {
	"brand": "Ford",
 	"model": "Mustang",
 	"year": 1964
}

#Assigning a value
thisdict["year"] = 2018
Posted by: Guest on November-27-2019
3

python dictionary methods

# PYTHON DICTIONARY METHODS
METHOD	      DESCRIPTION
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
Posted by: Guest on April-19-2021
10

how to create a dictionary in python

thisdict = {
  "key1" : "value1"
  "key2" : "value2"
  "key3" : "value3"
  "key4" : "value4"
}
Posted by: Guest on May-17-2020
11

dictionary in python

thisdictionary = {'key':'value','key1':'value1'}
print(thisdictionary['key'])
Posted by: Guest on March-24-2020
-4

python dictionary methods

dictionary methods
Posted by: Guest on March-06-2021

Python Answers by Framework

Browse Popular Code Answers by Language