Skip to content

Instantly share code, notes, and snippets.

@mGalarnyk
Last active June 23, 2017 07:53
Show Gist options
  • Save mGalarnyk/a1040983df26e9c49a883719ca9fe64c to your computer and use it in GitHub Desktop.
Save mGalarnyk/a1040983df26e9c49a883719ca9fe64c to your computer and use it in GitHub Desktop.
Python dictionary and dictionary manipulation tutorial for the blog post: https://medium.com/@GalarnykMichael/python-basics-10-dictionaries-and-dictionary-methods-4e9efa70f5b9
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<h1 align=\"center\"> Dictionaries </h1>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Dictionaries are unordered data structures that map keys into values. The value can be anything (lists, functions, strings, anything). The key has to be immutable, for example, numbers, strings or tuples."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example\n",
"dictionary: word we look up is key, look up is definition (value)"
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Defining a dictionary\n",
"webstersDict = {'person': 'a human being, whether an adult or child', 'marathon': 'a running race that is about 26 miles', 'resist': ' to remain strong against the force or effect of (something)', 'run': 'to move with haste; act quickly'}"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'marathon': 'a running race that is about 26 miles',\n",
" 'person': 'a human being, whether an adult or child',\n",
" 'resist': ' to remain strong against the force or effect of (something)',\n",
" 'run': 'to move with haste; act quickly'}"
]
},
"execution_count": 112,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"webstersDict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Accessing Values in a Dictionary"
]
},
{
"cell_type": "code",
"execution_count": 113,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'a running race that is about 26 miles'"
]
},
"execution_count": 113,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Finding out the meaning of the word marathon\n",
"# dictionary[key]\n",
"webstersDict['marathon']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Updating Dictionary"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'an external covering for the human foot'"
]
},
"execution_count": 114,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# add one new key value pair to dictionary\n",
"webstersDict['shoe'] = 'an external covering for the human foot'\n",
"\n",
"# return the value for the 'shoe' key\n",
"webstersDict['shoe']"
]
},
{
"cell_type": "code",
"execution_count": 115,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'marathon': 'a running race that is about 26 miles',\n",
" 'person': 'a human being, whether an adult or child',\n",
" 'resist': ' to remain strong against the force or effect of (something)',\n",
" 'run': 'to move with haste; act quickly',\n",
" 'shirt': 'a long- or short-sleeved garment for the upper part of the body',\n",
" 'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'}"
]
},
"execution_count": 115,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# update method, update or add more than key value pair at a time \n",
"webstersDict.update({'shirt': 'a long- or short-sleeved garment for the upper part of the body'\n",
" , 'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'})\n",
"webstersDict"
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'marathon': 'a running race that is about 26 miles',\n",
" 'person': 'a human being, whether an adult or child',\n",
" 'run': 'to move with haste; act quickly',\n",
" 'shirt': 'a long- or short-sleeved garment for the upper part of the body',\n",
" 'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'}"
]
},
"execution_count": 116,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Removing key from dictionary\n",
"del webstersDict['resist']\n",
"webstersDict"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Not Everything can Be Used as a Key"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Only immutable objects can be used as keys. Lists cannot be used as keys, but tuples, numbers, and strings can."
]
},
{
"cell_type": "code",
"execution_count": 117,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "unhashable type: 'list'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-117-95ef7f324c79>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mwebstersDict\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'sock'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'a short stocking usually reaching to the calf or just above the ankle.'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: unhashable type: 'list'"
]
}
],
"source": [
"webstersDict[['sock']] = 'a short stocking usually reaching to the calf or just above the ankle.'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Returning Values for a Given Key using the get() Method"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You will see why this is so valuable in the word count task"
]
},
{
"cell_type": "code",
"execution_count": 118,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# incorporate into get example and such below. \n",
"storyCount = {'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}"
]
},
{
"cell_type": "code",
"execution_count": 119,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Michael': 12, 'is': 100, 'runs': 5, 'the': 90}"
]
},
"execution_count": 119,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"storyCount"
]
},
{
"cell_type": "code",
"execution_count": 120,
"metadata": {},
"outputs": [
{
"ename": "KeyError",
"evalue": "'run'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-120-7457d9dbff5f>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# key error for keys that do not exist\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mstoryCount\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'run'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mKeyError\u001b[0m: 'run'"
]
}
],
"source": [
"# key error for keys that do not exist\n",
"storyCount['run']"
]
},
{
"cell_type": "code",
"execution_count": 121,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"12"
]
},
"execution_count": 121,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# if key doesnt exist, \n",
"# specify default value for keys that dont exist. \n",
"# returns value for key you enter if it is in dictionary\n",
"# else it returns the value you have for default\n",
"storyCount.get('Michael', 0)"
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"# When you dont set default value for key that doesnt exist, \n",
"# it defaults to none\n",
"print(storyCount.get('run'))"
]
},
{
"cell_type": "code",
"execution_count": 123,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n"
]
}
],
"source": [
"# Making default value for key that doesn't exist 0. \n",
"print(storyCount.get('run', 0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Remove key, but also return the Value"
]
},
{
"cell_type": "code",
"execution_count": 124,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"90\n"
]
}
],
"source": [
"count = storyCount.pop('the')\n",
"print(count)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Iterating through Dictionaries"
]
},
{
"cell_type": "code",
"execution_count": 125,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['is', 'runs', 'Michael']\n",
"[100, 5, 12]\n"
]
}
],
"source": [
"# return keys in dictionary\n",
"print(storyCount.keys())\n",
"\n",
"# return values in dictionary\n",
"print(storyCount.values())"
]
},
{
"cell_type": "code",
"execution_count": 126,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"is\n",
"runs\n",
"Michael\n"
]
}
],
"source": [
"# iterate through keys\n",
"for key in storyCount: \n",
" print(key)"
]
},
{
"cell_type": "code",
"execution_count": 127,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('person', 'a human being, whether an adult or child')\n",
"('run', 'to move with haste; act quickly')\n",
"('shoe', 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.')\n",
"('marathon', 'a running race that is about 26 miles')\n",
"('shirt', 'a long- or short-sleeved garment for the upper part of the body')\n"
]
}
],
"source": [
"# iterate through keys and values\n",
"for key, value in webstersDict.items():\n",
" print(key, value)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**if this tutorial doesn't cover what you are looking for, please leave a comment on the youtube video and I will try to cover what you are interested in. (Please subscribe if you can!)**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"https://www.youtube.com/watch?v=LlIqrWJaBcQ"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [default]",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment