DICTIONARY QUESTIONS Flashcards

1
Q

Dictionary?

A

In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Create a new dictionary

A

Create a new dictionary
d = dict()
# or you can do
d = {}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Add a key - value pairs to dictionary

A

Add a key - value pairs to dictionary
d[‘xyz’] = 123
d[‘abc’] = 345
returns {‘xyz’: 123, ‘abc’: 345}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

print the whole dictionary

A

print the whole dictionary
print(d)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

print only the keys

A

A
# print only the keys
print(d.keys())
returns [‘key1’, ‘key2’,…]
#notice the parens around the keys

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

print only values

A

print only values
print(d.values())
returns [value1, value2]
#notice the lack of parens around the values

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

iterate over dictionary

A

iterate over dictionary
for i in d :
print(“%s %d” %( i, d[i] ) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

another way of iteration over a dictionary

A

another method of iteration
for index, value in enumerate(d):
print (index, value , d[value])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

check if key exist

A

check if key exist
print(‘xyz’ in d)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

delete the key-value pair

A

delete the key-value pair
del d[‘xyz’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Dict.cmp()

A

Dict.cmp(): Compares elements of both dict.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Dict.len()

A

Dict.len(): Gives the total length of the dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Dict.str()

A

Dict.str(): Produces a printable string representation of a dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Dict.type()

A

Dict.type(): Returns the type of the passed variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Dict.clear()

A

Dict.clear(): Removes all elements of dictionary dict

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Dict.copy()

A

Dict.copy(): Returns a shallow copy of dictionary dict