Skip to content

Instantly share code, notes, and snippets.

@kylepjohnson
Created April 8, 2016 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylepjohnson/6f5fe53202f40ab7c1e6a35109734865 to your computer and use it in GitHub Desktop.
Save kylepjohnson/6f5fe53202f40ab7c1e6a35109734865 to your computer and use it in GitHub Desktop.
Example to page through dict
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"d = {3: 'something', 2: 'something else', 1: 'starting'}"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3]\n"
]
}
],
"source": [
"key_list = sorted(d.keys())\n",
"print(key_list)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Current value for index 0:\n",
" \"starting\"\n",
"Previous value for index 0:\n",
" \"None\"\n",
"Next value for index 0:\n",
" \"something else\"\n",
"Current value for index 1:\n",
" \"something else\"\n",
"Previous value for index 1:\n",
" \"starting\"\n",
"Next value for index 1:\n",
" \"something\"\n",
"Current value for index 2:\n",
" \"something\"\n",
"Previous value for index 2:\n",
" \"something else\"\n",
"Next value for index 2:\n",
" \"None\"\n"
]
}
],
"source": [
"for i, key in enumerate(key_list):\n",
" print('Current value for index {}:'.format(i))\n",
" current_value = d[key_list[i]]\n",
" print(' \"{}\"'.format(current_value))\n",
"\n",
" print('Previous value for index {}:'.format(i))\n",
" previous_index = i - 1\n",
" if previous_index < 0:\n",
" previous_index = None\n",
" try:\n",
" previous_value = d[key_list[previous_index]]\n",
" except TypeError:\n",
" previous_value = None\n",
" print(' \"{}\"'.format(previous_value))\n",
" \n",
" print('Next value for index {}:'.format(i))\n",
" try:\n",
" next_value = d[key_list[i + 1]]\n",
" except IndexError:\n",
" next_value = None\n",
" print(' \"{}\"'.format(next_value))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.0"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment