如何在词典上动态迭代

发布于 2025-02-08 19:38:53 字数 1077 浏览 1 评论 0原文

如何使用动态查询在字典 / 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

要走干脆点 2025-02-15 19:38:53

我做出了一些假设,例如,'/'不是任何dict-keys的一部分,该路径必须有效。根据需要调整功能。

def deep_set(d, path, value):
    sep = '/'
    *trail, last = path.strip(sep).split(sep)
    
    for part in trail:
        d = d[part]
        
    d[last] = value

演示:

>>> d = {'a': 1}
>>> deep_set(d, 'a', 2)
>>> d
{'a': 2}
>>> d = {'a': {'b': 1}}
>>> deep_set(d, 'a/b', 2)
>>> d
{'a': {'b': 2}}

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.

def deep_set(d, path, value):
    sep = '/'
    *trail, last = path.strip(sep).split(sep)
    
    for part in trail:
        d = d[part]
        
    d[last] = value

Demo:

>>> d = {'a': 1}
>>> deep_set(d, 'a', 2)
>>> d
{'a': 2}
>>> d = {'a': {'b': 1}}
>>> deep_set(d, 'a/b', 2)
>>> d
{'a': {'b': 2}}

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 with str.strip). Again, adjust as needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文