如何在词典上动态迭代
如何使用动态查询在字典 / JSON上迭代。
例如,请考虑以下dict
dict = {'Adam': {
'English': {
'Score': 99,
'Time': 3400,
'Classes': 4},
'Math': {
'Score': 45,
'Time': 779,
'Classes': 5}},
'Tim': {
'English': {
'Score': 74,
'Time': 12,
'Classes': 99},
'Math': {
'Score': 12,
'Time': 333,
'Classes': 1}}
}
我想设置给定路径的值,例如,
path = '/Adam/English/Score'
new_value = 87
请注意,分配的值也可能是另一个dict,例如
path = '/Adam/English'
new_value = {'Score': 11,
'Time': 2,
'Classes': 9}
任何帮助都是有用的。
编辑:以下是我的
keys = path.split('/')[1:]
new_data = None
for key in keys:
if new_data is None:
new_data = dict[key]
else:
new_data = new_data[key]
new_data = new_value
print(dict)
尝试
How to iterate over a dictionary / JSON using a dynamic query.
For example consider the below dict
dict = {'Adam': {
'English': {
'Score': 99,
'Time': 3400,
'Classes': 4},
'Math': {
'Score': 45,
'Time': 779,
'Classes': 5}},
'Tim': {
'English': {
'Score': 74,
'Time': 12,
'Classes': 99},
'Math': {
'Score': 12,
'Time': 333,
'Classes': 1}}
}
I want to set the value of a given path for example
path = '/Adam/English/Score'
new_value = 87
Note that the value assigned could be another dict as well for example
path = '/Adam/English'
new_value = {'Score': 11,
'Time': 2,
'Classes': 9}
Any help would be useful.
Edit: Below is my attempt
keys = path.split('/')[1:]
new_data = None
for key in keys:
if new_data is None:
new_data = dict[key]
else:
new_data = new_data[key]
new_data = new_value
print(dict)
But here the dict
still has the old value
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我做出了一些假设,例如,
'/'
不是任何dict-keys的一部分,该路径必须有效。根据需要调整功能。演示:
edit:
请注意,如果有连续的
'/'
字符,则将“空字符串”视为dict键。例如'a/b // c'.split('/') - > ['a','b','','c']
尚不清楚您是否要将领先/trailling
'/'
字符作为路径的一部分(在我的功能,用str.Strip
删除它们。再次,根据需要进行调整。I made some assumptions, for example that
'/'
is not part of any dict-keys and that the path must be valid. Adjust the function as needed.Demo:
edit:
Note that if there are consecutive
'/'
characters then the empty string will be looked up as a dict key. e.g.'a/b//c'.split('/') -> ['a', 'b', '', 'c']
It's unclear whether you want to treat leading/trailling
'/'
characters as part of the path or not (in my function, they are removed withstr.strip
). Again, adjust as needed.