0

I have a Json list and I want to print all the keys from a given key till the end of dictionary. But the code I wrote is very complex. How to do it with less complexity ? I'm using Python 3

dictionary = [{"a": "1"}, {"b": "2"}, {"c": "3"}, {"d": "4"}]

try:
    for token in dictionary:
            if "b" in list(token.keys())[0]:
                new_dict = dictionary[len(list(token.keys())[0]):]
                for i in new_dict:
                    print(new_dict[len(list(i.keys())[0]):])
                break
            else:
                print("Inception")
except Exception as error:
    print(str(error))

DESIRED
Input: b
Output: c, d

My Output:

Inception
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
LITDataScience
  • 380
  • 5
  • 14

3 Answers3

5

Use itertools.dropwhile() to skip all dictionaries that don't have a 'b' key:

from itertools import dropwhile

filtered = dropwhile(lambda t: 'b' not in t, dictionary)
next(filtered)  # skip the dictionary with `b` in it.

for token in filtered:
    print(token)

This prints all dictionaries after the first. If you only need to print their keys, do so explicitly:

filtered = dropwhile(lambda t: 'b' not in t, dictionary)
next(filtered)  # skip the dictionary with `b` in it.

for token in filtered:
    print(*token, sep='\n')

This prints the keys on separate lines; if there is just one key, then that's all that'll be printed for each token dictionary.)

As a side note: you really do not want to use list(dict.keys())[0]. Before Python 3.6, dictionaries have no set order (instead being subject to insertion and deletion history and the current random hash seed), so if you have more than one key what value you'll get is a gamble. And all you want to do is see if a key is present, so use a key in dictobject membership test.

To get the first key out of each dictionary, I'd use next(iter(dictobject)), avoiding creating a list:

first_key = next(iter(dictobject))

I'd only use this if I had single-key dictionaries. I'd also avoid using dictionaries for such a scenario; perhaps you really wanted to use an ordered dictionary instead (in Python < 3.6, use collections.OrderedDict(), otherwise use the regular dict type).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

This is one way. The idea is to find the index of the dictionary with desired key. Then filter your list accordingly.

keys = [next(iter(x)) for x in dictionary]
res = keys[keys.index('b')+1:]
# ['c', 'd']
jpp
  • 159,742
  • 34
  • 281
  • 339
0

You can re-write your code as follows for your desired result.

found = False
for data in dictionary:
    if found:
        print(list(data.keys())[0])
    if 'b' in data.keys():
        found = True
akhilsp
  • 1,063
  • 2
  • 13
  • 26