Documente Academic
Documente Profesional
Documente Cultură
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a
dictionary can be of any type, but the keys must be of an immutable data type
such as strings, numbers, or tuples.
Accessing Values in Dictionary:
To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value. Following is a simple example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
1 M.Lawanyashri, SITE
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
2 M.Lawanyashri, SITE
Inserting key(s) and corresponding value(s):
3 M.Lawanyashri, SITE
Accessing key and values:
Updating elements:
4 M.Lawanyashri, SITE
Deleting elements:
5 M.Lawanyashri, SITE
Deleting dictionary item using pop:
In operator : will check only for key not for value in dictionary:
6 M.Lawanyashri, SITE
Create a new list of dictionary ys keys:
Update method :
Nesting:
Dictionary inside dictionary
7 M.Lawanyashri, SITE
Accessing nested elements:
Comprehensions in Dictionaries:
8 M.Lawanyashri, SITE
Python program that gets values
plants = {}
# Get syntax 1.
print(plants["radish"])
# Get syntax 2.
print(plants.get("tuna"))
print(plants.get("tuna", "no tuna found"))
Output
2
None
no tuna found
print("Keys:")
print(keys)
print(len(keys))
9 M.Lawanyashri, SITE
print("Values:")
print(values)
print(len(values))
Output
Keys:
dict_keys(['home', 'about', 'sitemap'])
3
Values:
dict_values([125, 43, 27])
3
frequencies = {}
for c in letters:
# If no key exists, get returns the value 0.
# ... We then add one to increase the frequency.
# ... So we start at 1 and progress to 2 and then 3.
frequencies[c] = frequencies.get(c, 0) + 1
for f in frequencies.items():
# Print the tuple pair.
print(f)
Output
('a', 2)
('c', 2)
('b', 2)
('e', 1)
10 M.Lawanyashri, SITE
('d', 1)
('g', 1)
('f', 1)
('i', 1)
('h', 1)
n=int(input())
d={}
for I in range(0,n):
k=input()
v=int(input())
d[k]=v
print(d)
ke=list(d.keys())
val=list(d.values())
print(ke)
print(val)
11 M.Lawanyashri, SITE
12 M.Lawanyashri, SITE