gpt4 book ai didi

python - 我怎样才能得到一个字典来生成两个具有相同键的字典

转载 作者:太空宇宙 更新时间:2023-11-04 04:53:32 24 4
gpt4 key购买 nike

我有一本字典,什么:

what = {'a': ['b'], 'c': ['d\n', 'e\n', 'f'], 'd': ['f', 'g']}

并且需要将带有 '/n' 和不带有 '/n' 的项目分开(顺序很重要,需要对值进行排序。):

[[{'a': ['b'], 'c': ['f'], 'd': ['f', 'g']}], [{'c': ['d\n', 'e\n']}]]

这是我尝试过的:

    def lst(profiles_file: TextIO):
solve_lst = []
new_lst = fix_files(profiles_file)
for k, v in new_lst.items():
for i in v:
if i.find('\n') != -1:
get_index = [v.index(i)]
solve_lst.append(get_index)
return solve_lst

我怎样才能在不做任何复杂的事情的情况下得到这个?

最佳答案

这是一个使用 defaultdict 的解决方案

from collections import defaultdict

def lst(profiles_file: TextIO):
initial_dict = fix_files(profiles_file)

with_n = defaultdict(list)
without_n = defaultdict(list)

for k, v in initial_dict.items():
for item in v:
if '\n' in item:
with_n[k].append(item)
else:
without_n[k].append(item)

return [without_n, with_n]

关于python - 我怎样才能得到一个字典来生成两个具有相同键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47623398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com