Dictionaries Flashcards

1
Q

Create a dictionary

A

dictionary = { “key1”: “value1”, “key2”: “value2”}

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

Access value by key in dictionary

A

dictionary[“key1”]

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

Add of update key value pair

A

dictionary[“key3”] = “value3”

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

Delete key value pair

A

del dictionary[“key1”]

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

Check if key exists

A

‘key1’ in dictionary

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

Get list of keys in dictionary

A

list(dictionary.keys())

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

Get list of values in dictionary

A

list(dictionary.values())

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

Update dictionary with elements from another dictionary, if key already exists, its value is updated, if the key doesn’t exist, it is added

A

dictionary.update(another_dictionary)

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

If key doesn’t exist set default value

A

dictionary.setdefault(‘key’, ‘default_value’)

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

Create a dictionary from array of keys with default value

A

dict.fromkeys(arr, value)

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

Remove key from dictionary and return value

A

dictionary.pop(‘key’)

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

Remove and return the last inserted key-value pair as a tuple

A

key, value = dictionary.popitem()

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

Loop through keys in dictionary

A

for key in my_dict:
print(key)

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

Loop through both key and value in dictionary

A

for key, value in my_dict.items():
print(key, value)

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