LIT*_*nce 0 python json dictionary python-3.x
我有一个Json列表,我想从给定的键打印所有键,直到字典结束.但是我写的代码非常复杂.如何以较低的复杂性做到这一点?我正在使用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))
Run Code Online (Sandbox Code Playgroud)
希望
输入:b
输出:c,d
我的输出:
Inception
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
Run Code Online (Sandbox Code Playgroud)
使用itertools.dropwhile()跳过不具有的所有字典'b'键:
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)
Run Code Online (Sandbox Code Playgroud)
这将在第一个之后打印所有词典.如果您只需要打印他们的密钥,请明确地这样做:
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')
Run Code Online (Sandbox Code Playgroud)
这会将键打印在不同的行上; 如果只有一个键,则为每个token字典打印所有内容.)
作为旁注:你真的不想使用list(dict.keys())[0].在Python 3.6之前,字典没有设置顺序(而是受插入和删除历史记录以及当前随机哈希种子的影响),因此如果您有多个密钥,那么您将得到的是一个赌博.您要做的就是查看是否存在密钥,因此请使用key in dictobject成员资格测试.
为了从每个字典中获取第一个密钥,我将使用next(iter(dictobject)),避免创建列表:
first_key = next(iter(dictobject))
Run Code Online (Sandbox Code Playgroud)
如果我有单键字典,我只会使用它.我也避免在这种情况下使用词典; 也许你真的想要使用有序字典(在Python <3.6中,使用collections.OrderedDict(),否则使用常规dict类型).