从列表指向字典变量 [英] point from a list into a dicitonary variable

查看:45
本文介绍了从列表指向字典变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个列表

a = [3,4,1]

我想用这些信息指向字典:

I want with this information to point to the dictionary:

b[3][4][1]

现在,我需要的是一个例程.在我看到该值后,在 b 的位置内读取和写入一个值.

Now, what I need is a routine. After I see the value, to read and write a value inside b's position.

我不喜欢复制变量.我想直接更改变量 b 的内容.

I don't like to copy the variable. I want to change variable b's content directly.

推荐答案

假设 b 是一个嵌套字典,你可以这样做

Assuming b is a nested dictionary, you could do

reduce(dict.get, a, b)

访问b[3][4][1].

对于更一般的对象类型,使用

For more general object types, use

reduce(operator.getitem, a, b)

写入值有点复杂:

reduce(dict.get, a[:-1], b)[a[-1]] = new_value

所有这些都假设您现在不知道 a 中的元素数量.如果你这样做了,你可以选择 neves 的回答.

All this assumes you don't now the number of elements in a in advance. If you do, you can go with neves' answer.

这篇关于从列表指向字典变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆