Python - Dictionaries


  • Dictionaries are an unordered collection, the key could be added anywhere. (this leads to better performance)
  • Keys have to be immutable
  • Cannot mutate/remove keys 



Dictionaries



Dictionaries are data structures used to map arbitrary keys to values. 
Lists can be thought of as dictionaries with integer keys within a certain range.
Dictionaries can be indexed in the same way as lists, using square brackets containing keys.
Example:
ages = {"Dave": 24, "Mary": 42, "John": 58}
print(ages["Dave"])
print(ages["Mary"])
Each element in a dictionary is represented by a key:value pair.

Trying to index a key that isn't part of the dictionary returns a KeyError.
Example:
primary = {
"red": [255, 0, 0],
"green": [0, 255, 0],
"blue": [0, 0, 255],
}

print(primary["red"])
print(primary["yellow"])
As you can see, a dictionary can store any types of data as values.
An empty dictionary is defined as {}.

Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can't be changed. we can,t use mutable objects like lists and dictionaries. Trying to use a mutable object as a dictionary key causes a TypeError.
bad_dict = {
[1, 2, 3]: "one two three",
}
Dictionary Functions

Just like lists, dictionary keys can be assigned to different values.
However, unlike lists, a new dictionary key can also be assigned a value, not just ones that already exist.
squares = {1: 1, 2: 4, 3: "error", 4: 16,}
squares[8] = 64
squares[3] = 9
print(squares)
Result:{1: 1, 2: 4, 3: 9, 4: 16, 8: 64}
IN and NOT IN

To determine whether a key is in a dictionary, you can use in and not in, just as you can for a list.
Example:
nums = {
1: "one",
2: "two",
3: "three",
}
print(1 in nums)
print("three" in nums)
print(4 not in nums)
GET
A useful dictionary method is get. It does the same thing as indexing, but if the key is not found in the dictionary it returns another specified value instead ('None', by default).Example:
pairs = {1: "apple",
"orange": [2, 3, 4],
True: False,
None: "True",
}

print(pairs.get("orange"))
print(pairs.get(7))
print(pairs.get(12345, "not in dictionary"))
paris.pop[1]   --- will remove key 1 and returns it value  which could be stored in a variable.

del paris['Orange']    --- will delete the key from tupel pairs without returning any value





Comments

Popular posts from this blog

Python - Argument Passing

Python - How to Escape special characters in String