給出以下清單:
mapping_list = ['location/name', 'location/address/address1', 'location/address/zip'/span>, 'location/business/business_name'/span>, 'occupant/occupant_type'/span>]
如何把它變成一個嵌套的字典,如下所示,最后一個值是最后一個鍵,默認值是一個空字串。
{
"location":
{
"name": ""。
"地址":
{
"address1": "",
"zip": "".
},
"business":
{
"business_name": ""
}
},
" occupant":
{
" occupant_type": ""。
}
}
注意:給定的串列可以寫成這樣:
mapping_list_of_lists = [] 。
for full_path in mapping_list:
path_list = full_path.split('/')
mapping_list_of_lists.append(path_list)
print(mapping_list_of_lists)
[['location', 'name'], ['location', 'address', 'address1'], ['location', 'address', 'zip'], ['地點', '企業', '企業名稱'], ['居住者', '居住者型別']]
uj5u.com熱心網友回復:
我相信有更好的方法,但你可以寫一個遞回函式,用一個映射來填充給定的dict,比如你的映射。
mapping_list = [
'location/name'。
'location/address/address1',
'location/address/zip'。
'location/business/business_name'。
' occupant/occupant_type'def populate(mapping, dct, default=')。
# check if '/' is in your current mapping.
if '/' in mapping:
pos = mapping.find('/')
part = mapping[:pos]
# if it is and the next dict level does not exist yet;
# 創建空的dict并遞回呼叫。
# 函式來填充內部部分。
# 剩余的映射。
if part not in dct:
dct[part] = dict()
populate(mapping[pos 1:], dct[part], default=default)
# otherwise, you're on your last part[/span
# 并且可以安全地填充默認值。
else。
dct[mapping] = default
dct = {}。
for mapping in mapping_list:
populate(mapping, dct)
print(dct)
利用str.split('/')的替代方法:
mapping_list = [
'location/name'。
'location/address/address1',
'location/address/zip'。
'location/business/business_name'。
' occupant/occupant_type'def populate(mapping, dct, default=')。
if len(mapping) > 1:
if mapping[0] not in dct:
dct[mapping[0]] = dict()
populate(mapping[1:], dct[mapping[0], default=default)
else:
dct[mapping[0]] = default
mapping_list_of_lists = [i.split('/') for i in mapping_list]
dct = {}。
for part in mapping_list_of_lists:
populate(part, dct)
print(dct)
uj5u.com熱心網友回復:
我認為setdefault()可以很好地解決這個問題,盡管你也可以使用一個嵌套的collections.defaultdict()。我認為唯一的問題是,在最后的葉子中,你想要一個空字串,而不是一個空的dict,否則這將是非常簡單。
mapping_list = [
'location/name'。
'location/address/address1'。
'location/address/zip'。
'location/business/business_name'。
' occupant/occupant_type'for keys in [keys.split("/") for keys in mapping_list] 。
tmp = result
for index, key in enumerate(keys)。
default = "" if index ==(len(keys) -1) else {}.
tmp = tmp.setdefault(key, default)
print(result)
這將給你:
{'location': {'name': '', '地址': {'地址1': '', 'zip': ''/span>}, 'business': {'business_name': ''}}, ' occupant': {' occupant_type': ''}}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/311647.html
標籤:
下一篇:Python中方括號的含義
