Python: how to slice a dictionary based on the values of its keys? -


say have dictionary built this:

d={0:1, 1:2, 2:3, 10:4, 11:5, 12:6, 100:7, 101:8, 102:9, 200:10, 201:11, 202:12}

and want create subdictionary d1 slicing d in such way d1 contains following keys: 0, 1, 2, 100, 101, 102. final output should be:

d1={0:1, 1:2, 2:3, 100:7, 101:8, 102:9}

is there efficient pythonic way of doing this, given real dictionary contains on 2,000,000 items?

i think question applies cases keys integers, when slicing needs follow inequality rules, , when final result needs bunch of slices put in same dictionary.

you use dictionary comprehension with:

d = {0:1, 1:2, 2:3, 10:4, 11:5, 12:6, 100:7, 101:8, 102:9, 200:10, 201:11, 202:12} keys = (0, 1, 2, 100, 101, 102) d1 = {k: d[k] k in keys} 

in python 2.7 can compute keys (in python 3.x replace it.ifilter(...) filter(...)):

import itertools  d = {0:1, 1:2, 2:3, 10:4, 11:5, 12:6, 100:7, 101:8, 102:9, 200:10, 201:11, 202:12} d1 = {k: d[k] k in it.ifilter(lambda x: 1 < x <= 11, d.keys())} 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -