|
430 | 430 | "cell_type": "markdown",
|
431 | 431 | "metadata": {},
|
432 | 432 | "source": [
|
433 |
| - "Like in the above example, if in the following year we want to increment the age of each person by `1`, we can basically do this as an update operation. We can see that the previous age values of `42` and `38` and respectively revised to `43` and `39`" |
| 433 | + "Like in the above example, if in the following year we want to increment the age of each person by `1`, we can basically do this as an update operation. We can see that the previous age values of `42` and `38` and respectively revised to `43` and `39`\n", |
| 434 | + "\n", |
| 435 | + "## Understanding key and value types\n", |
| 436 | + "\n", |
| 437 | + "A dict can essentially store any value. Anything that is an object in Python can be stored as a value in the dict. This includes the fact that even functions can be stored as values. \n", |
| 438 | + "\n", |
| 439 | + "Keys of a dict can also be of any object type; but only as long as the object is immutable. A mutable object cannot be stored as a dict. Let's look at some examples. " |
| 440 | + ] |
| 441 | + }, |
| 442 | + { |
| 443 | + "cell_type": "code", |
| 444 | + "execution_count": 15, |
| 445 | + "metadata": {}, |
| 446 | + "outputs": [ |
| 447 | + { |
| 448 | + "name": "stdout", |
| 449 | + "output_type": "stream", |
| 450 | + "text": [ |
| 451 | + "{('Tom', 'Mike'): (42, 38), ('Harry', 'Alice'): [40, 36], 'Tom': 43, 'Mike': 39}\n" |
| 452 | + ] |
| 453 | + } |
| 454 | + ], |
| 455 | + "source": [ |
| 456 | + "dict1 = {('Tom', 'Mike'): (42,38), ('Harry', 'Alice'): [40,36]}\n", |
| 457 | + "dict1.update(nextYear)\n", |
| 458 | + "print(dict1)" |
| 459 | + ] |
| 460 | + }, |
| 461 | + { |
| 462 | + "cell_type": "markdown", |
| 463 | + "metadata": {}, |
| 464 | + "source": [ |
| 465 | + "In the above example `('Tom', 'Mike')` is the key of the dict and `(42,38)` is the value. In the second record, we have used an array of `[40,36]` instead of a tuple. \n", |
| 466 | + "\n", |
| 467 | + "We can use `(42,38)` as a key, but we cannot use `[42,38]` as a key. This is because the first is a tuple and a tuple is immutable, but the second is a list which is mutable. A mutable cannot be used as a key, as the object does not have a definite value; which when changed would require the dict to be completely re-keyed, which would be undesirable. " |
434 | 468 | ]
|
435 | 469 | }
|
436 | 470 | ],
|
|
0 commit comments