【发布时间】:2018-11-12 07:19:45
【问题描述】:
我有一个字典,它可以包含任意顺序的字符串、字符串列表或最终以字符串结尾的嵌套字典。我想遍历这个字典并对每个字符串执行一个操作。
This 问题与我正在寻找的问题很接近,但我未能成功地将该解决方案应用于我自己的问题。
我需要将函数os.path.expanduser() 应用于以下字典中的每个字符串:
x = dict(
dir = dict(
wd = '~/Desktop/WD',
pymodule = [
'~/Documents/PythonModule',
'/Users/Username/Documents/PythonModule2'
],
album = '~/Desktop/Album'
),
file = dict(
XML = '~/Downloads/data.xml',
CSV = '~/Downloads/data.csv'
)
)
理想情况下,我想定义一个类,当在普通字典上调用时,将在该字典的每个字符串元素上应用 os.path.expanduser()。
class MyDict:
def __init__(d):
self.d = d
# some operation to apply os.path.expanduser() on each string element of 'd'
我怎样才能做到这一点?
【问题讨论】:
标签: python dictionary