1

I have dictionary like:

{0:'I', 3: 'Mr.', 5: 'Nevrekar', 8: 'JK', 14: 'Soham', 15: 'Sharma',  4: 'Akshay'}

I want to return it the 1st combination of consecutive keys(minimum 2). In above case it's (3,4,5).

so it would return a list:

['Mr.', 'Akshay', 'Nevrekar'].

How can I achieve this?

My Attempt:

name=[]
count = 0
for k,g in name_list.items():
    if count == 0:
        temp =None
    if k-1 == temp:
        name.append(g)

    count+= 1
    temp = k

which is giving output as:

['Akshay', 'Nevrekar', 'Sharma']
Sociopath
  • 13,068
  • 19
  • 47
  • 75

2 Answers2

1

There is a recipe from more_itertools that comes in handy here:

import more_itertools as mit

d = {0:'I', 3: 'Mr.', 4: 'Akshay', 5: 'Nevrekar', 8: 'JK', 14: 'Soham', 15: 'Sharma'}
cons = [list(group) for group in mit.consecutive_groups(sorted(d.keys()))]
# [[0], [3, 4, 5], [8], [14, 15]]
res = [[d[y] for y in x] for x in cons if len(x)>1]
# [['Mr.', 'Akshay', 'Nevrekar'], ['Soham', 'Sharma']]

If you only need groups where the consecutive integers are at least 3 you have to modify the inequality accordingly (len(x) > 2).

Ma0
  • 15,057
  • 4
  • 35
  • 65
0

From the docs:

>>> a = {0:'I', 3: 'Mr.', 4: 'Akshay', 5: 'Nevrekar', 8: 'JK', 14: 'Soham', 15: 'Sharma'}
>>>
>>> 
>>> from itertools import groupby
>>> from operator import itemgetter
>>>
>>> con_ser = None
>>> for k, g in groupby(enumerate(sorted(a.keys())), lambda (i,x):i-x):
...     item = map(itemgetter(1), g)
...     if(len(item) >= 3):
...             con_ser = item
...             break
... 
>>> 
>>> [a.get(x) for x in con_ser] .        #con_ser = [3, 4, 5]
['Mr.', 'Akshay', 'Nevrekar']
>>> 
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86