目標:~tag在復雜字典中將 a 添加到任何值的尾端,出現 %。
代碼適用于“淺”字典(沒有子字典)。我想使用任何復雜的字典。
注意:tag包括~,如果它發生。
代碼:
import re
import random
RE_TAG = re.compile(r". (~. )")
DLM = '~'
tag_occurance = 25 # as %
thisdict = {
"Key1~tag": "foo",
"Key2": "bar",
"Key3~tag": {
"Key3.1": "x",
"Key3.2~tag": "y"
}
}
def tag(_str):
m = RE_TAG.match(_str)
if m:
return DLM m[1][1:] # '~tag'
else:
return ''
# Main Process
thisdict = {key: val tag(key) if random.randint(0, 100) < tag_occurance else val for key, val in thisdict.items()} # 25% tag
print(thisdict) # view difference
錯誤:
val是它自己的字典,因此錯誤。
Traceback (most recent call last):
File "./prog.py", line 25, in <module>
File "./prog.py", line 25, in <dictcomp>
TypeError: unsupported operand type(s) for : 'dict' and 'str'
期望輸出:
{
"Key1~tag": "foo~tag", # tag added as postfix concatenated string
"Key2": "bar",
"Key3~tag": {
"Key3.1": "x",
"Key3.2~tag": "y~tag" # tag added as postfix concatenated string
}
}
錯誤原因
thisdict.values()回傳子字典。我只對它們的實際子值感興趣。
print(thisdict.values())
>>> dict_values(['foo', 'bar', {'Key3.1~tag': 'x', 'Key3.2~tag': 'y'}])
期望的迭代:
['foo', 'bar', 'x', 'y']
如果還有什么我可以添加到帖子中,請告訴我。
uj5u.com熱心網友回復:
正如評論中提到的,一種方法是撰寫一個遞回函式:
def nested_tag(d):
res = {}
for key, value in d.items():
if isinstance(value, dict):
res[key] = nested_tag(value)
else:
res[key] = value tag(key) if random.randint(0, 100) < tag_occurance else value
return res
final = nested_tag(this_dict)
print(final)
輸出
{'Key1~tag': 'foo', 'Key2': 'bar', 'Key3~tag': {'Key3.1': 'x', 'Key3.2~tag': 'y~tag'}}
上述解決方案假定唯一的復數值是字典。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/365727.html
上一篇:將一本字典轉換為字典串列
