Sunteți pe pagina 1din 12

Dictionary:

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'};

print "dict['Name']: ", dict['Name']


print "dict['Age']: ", dict['Age']

When the above code is executed, it produces the following result


dict['Name']: Zara
dict['Age']: 7
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below in
the 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

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire
contents of a dictionary. You can also delete entire dictionary in a single
operation.
To explicitly remove an entire dictionary, just use the del statement.
Following is a simple example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # remove entry with key 'Name'


dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

creating Empty dictionary:

2 M.Lawanyashri, SITE
Inserting key(s) and corresponding value(s):

Accessing dictionary values

In the above example L is long.

Accessing keys from dictionary

Error when accessing key using value (indexing)

3 M.Lawanyashri, SITE
Accessing key and values:

Updating elements:

4 M.Lawanyashri, SITE
Deleting elements:

Deleting dictionary x: will delete all the elements in x as well as x itself.

5 M.Lawanyashri, SITE
Deleting dictionary item using pop:

Remove all the elements

Finding length of dictionary

In operator : will check only for key not for value in dictionary:

6 M.Lawanyashri, SITE
Create a new list of dictionary ys keys:

Create a new list of dictionary ys values:

Update method :

Nesting:
Dictionary inside dictionary

7 M.Lawanyashri, SITE
Accessing nested elements:

Sorting : based on key, value and items:

Comprehensions in Dictionaries:

8 M.Lawanyashri, SITE
Python program that gets values

plants = {}

# Add three key-value tuples to the dictionary.


plants["radish"] = 2
plants["squash"] = 4
plants["carrot"] = 7

# 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

Python program that uses keys

hits = {"home": 125, "sitemap": 27, "about": 43}


keys = hits.keys()
values = hits.values()

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

Python that counts letter frequencies

# The first three letters are repeated.


letters = "abcabcdefghi"

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)

Dictionary example : to get key and value from the user


#getting name (key) and mobile number(value)

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

S-ar putea să vă placă și