python dictionary key value code example
Example 1: printing dictionary in python
mydict = {'score1': 41,'score2': 23}
mydict['score3'] = 45
for i in mydict:
print(i,mydict[i])
Example 2: python dictionary
dict1 = {'color': 'blue', 'shape': 'square', 'volume':40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter':15}
dict1['area'] = 25
dict2['perimeter'] = 20
print(dict1['shape'])
dict1.get('false_key')
dict1.get('false_key', "key not found")
dict1.pop('volume')
dict1.update(dict2)
dict1
dict1.values()
dict1.keys()
dict1.items()
Example 3: dictionary in python
programming_dictionary = {
"Bug": "An error in a program that prevents the program from running as expected.",
"Function": "A piece of code that you can easily call over and over again.",
"Loop": "The action of doing sommething again and again",
}
print(programming_dictionary["Function"])
for key in programming_dictionary:
print(programming_dictionary[key])
programming_dictionary["Variable"] = "The label to store some sort of data"
print(programming_dictionary["Variable"])
programming_dictionary["Variable"] = "Variables are nothing but reserved memory locations to store values. This means that when you create a variableyou reserve some space in memory"
Example 4: python make a dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Example 5: dictionaries in python 3
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
Example 6: dict value python
obj = {0:"hello", 1:"there"}
print(obj[0])
print(obj[1])
print("\n\n\n\n\n")
for i in range(len(obj)):
print(obj[i])