0

I have an nested OrderedDict data:

OrderedDict([('6',
          OrderedDict([('idx2', ['6', '6', '6']),
                       ('val2', ['A', 'T', 'T']),
                       ('val1', ['C', 'A', 'T']),
                       ('pos', ['11', '15', '23']),
                       ('idx1', ['4', '4', '4'])])),
         ('3',
          OrderedDict([('idx2', ['3', '3']),
                       ('val2', ['G', 'C']),
                       ('val1', ['A', 'G']),
                       ('pos', ['28', '34']),
                       ('idx1', ['4', '4'])])),
         ('4',
          OrderedDict([('idx2', ['4', '4']),
                       ('val2', ['T', 'C']),
                       ('val1', ['C', 'C']),
                       ('pos', ['41', '51']),
                       ('idx1', ['4', '4'])]))])

I can access the key, value pairs for each keys like:

for k, v in grouped_data.items():
    print(k, v)

and further nests using:

for k, v in grouped_data.items():
print(k, v)
for x in v.items():
    print(x)
    for z in x:
        print(z)

But, to process my data I need to access two consecutive keys at a time in a for loop: first 6-3 and then 3-4 and so on until the end.

I was thinking if I can index the key and get the keys, values after it:

for k, v in grouped_data.items():
    print(k, v)
    ind = grouped_data.keys().index(k)

Or,

for k, v in grouped_data.items():
    print(k, v)
    print(next(k))
Jonas
  • 121,568
  • 97
  • 310
  • 388
everestial007
  • 6,665
  • 7
  • 32
  • 72
  • 2
    In this case, I would `from itertools import islice` and iterate over `for k1, k2 in zip(data, islice(data, 1, None)): ...` – juanpa.arrivillaga Jan 11 '18 at 01:09
  • @juanpa.arrivillaga: And you can still iterate over the key/value pairs if you want, you just need a few extra parens for the nested unpacking: `for (k1, v1), (k2, v2) in zip(data.items(), islice(data.items(), 1, None)):` – ShadowRanger Jan 11 '18 at 01:21
  • 2
    BTW, `grouped_data.keys().index(k)` would only work on Python 2 (where `keys` returns a `list`), and it would be fairly wasteful there (you'd be making temporary lists `n` times, and scanning each one, making the work `O(n**2)`, rather than the `O(n)` work it actually requires). On Python 3, it returns a "view" of the keys, which is nearly free to make (unlike shallow copying all the keys to a temporary list), but doesn't support `list` methods like `index` at all. – ShadowRanger Jan 11 '18 at 01:23

0 Answers0