Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试将分层字符串结构放入dict_Python_Python 3.x_List - Fatal编程技术网

Python 尝试将分层字符串结构放入dict

Python 尝试将分层字符串结构放入dict,python,python-3.x,list,Python,Python 3.x,List,我对python非常陌生,现在已经有两天了,我正在努力将基于层次结构的字符串结构转换为python dict/list结构,以便更好地处理它: 示例字符串: Operating_System/Linux/Apache Operating_System/Linux/Nginx Operating_System/Windows/Docker Operating_System/FreeBSD/Nginx 我试图实现的是将每个字符串拆分并打包成一个python dict,这应该是 比如: {'Oper

我对python非常陌生,现在已经有两天了,我正在努力将基于层次结构的字符串结构转换为python dict/list结构,以便更好地处理它:

示例字符串:

Operating_System/Linux/Apache
Operating_System/Linux/Nginx
Operating_System/Windows/Docker
Operating_System/FreeBSD/Nginx
我试图实现的是将每个字符串拆分并打包成一个python dict,这应该是 比如:

{'Operating_System': [{'Linux': ['Apache', 'Nginx']}, {'Windows': ['Docker']}, {'FreeBSD': ['Nginx']}]}
我尝试了多种方法,包括zip()和一些通过字符串拆分(“/”)然后执行 它是通过嵌套迭代实现的,但我还不能解决它。有人知道一个好的/优雅的方法来实现吗 像这样的蟒蛇3

致以最良好的祝愿

克里斯

一个办法。。。您可以在此提供帮助:

#assumption is that it is a collection of strings
strings = ["Operating_System/Linux/Apache",
"Operating_System/Linux/Nginx",
"Operating_System/Windows/Docker",
"Operating_System/FreeBSD/Nginx"]

from collections import defaultdict
d = defaultdict(dict)
e = defaultdict(list)
m = [entry.split('/') for entry in strings]

print(m)

[['Operating_System', 'Linux', 'Apache'],
 ['Operating_System', 'Linux', 'Nginx'],
 ['Operating_System', 'Windows', 'Docker'],
 ['Operating_System', 'FreeBSD', 'Nginx']]

for a,b,c in m:
    e[b].append(c)
    d[a] = e

print(d)

defaultdict(dict,
            {'Operating_System': defaultdict(list,
                         {'Linux': ['Apache', 'Nginx'],
                          'Windows': ['Docker'],
                          'FreeBSD': ['Nginx']})})
如果您希望它们与您在输出中的共享完全相同,您可以跳过
defaultdict(dict)
部分:

mapp = {'Operating_System':[{k:v} for k,v in e.items()]}
mapp

{'Operating_System': [{'Linux': ['Apache', 'Nginx']},
  {'Windows': ['Docker']},
  {'FreeBSD': ['Nginx']}]
}


这也很有用

它们是单个字符串还是集中到单个字符串中?分隔符的数量是否固定为2,或者结果字典中的嵌套是否比示例中的嵌套更多?哇!非常感谢你。我不知道defaultdict,这很有帮助