matplotlib 如何将rcParams的键值对转换为字典

gwbalxhn  于 2023-11-22  发布在  其他
关注(0)|答案(2)|浏览(123)

我想得到rcParamskey:value对,以便进一步操作。

from matplotlib import rcParams 
x = rcParams
print(x)

字符串
叶尔兹:

_internal.classic_mode: False
agg.path.chunksize: 0
animation.bitrate: -1
animation.codec: h264
animation.convert_args: ['-layers', 'OptimizePlus']
animation.convert_path: convert
...


我尝试了这种方法:

for line in x:
    print(line)


它只产生了keys,而不是values

_internal.classic_mode
agg.path.chunksize
animation.bitrate
animation.codec
animation.convert_args
animation.convert_path
...


最后,我试着这样做:

for line in x:
    for key, value in line:
        print(key, value)


并收到以下错误:

ValueError: not enough values to unpack (expected 2, got 1)


接下来我应该尝试什么?

7gcisfzg

7gcisfzg1#

rcParams对象类型只是dict的子类,这意味着你仍然可以在rcParams对象上使用像.keys/.values/items这样的字典方法。

>>> from matplotlib import rcParams
>>> 
>>> isinstance(rcParams, dict)
True
>>> 
>>> print(*type(rcParams).__mro__, sep='\n')
<class 'matplotlib.RcParams'>
<class 'collections.abc.MutableMapping'>
<class 'collections.abc.Mapping'>
<class 'collections.abc.Collection'>
<class 'collections.abc.Sized'>
<class 'collections.abc.Iterable'>
<class 'collections.abc.Container'>
<class 'dict'>
<class 'object'>
>>> "keys" in dir(rcParams)
True
>>> "values" in dir(rcParams)
True
>>> "items" in dir(rcParams)
True

字符串
另请参阅:

sgtfey8w

sgtfey8w2#

rcParams是dict的一个子类,所以你应该已经能够在对象上执行dict方法了。也就是说,如果你需要像这样的一个类似dict的对象,并将其转换为一个单独的字典,你可以这样做:

from matplotlib import rcParams 

params = rcParams
new_params = {}

# with a simple for loop
for param in params:
    new_params[param] = params[param]
    
# or with the items() method
for param, value in params.items():
    new_params[param] = value

字符串

相关问题