Ваш подход с методом set имеет некоторые недостатки, например, неочевидное поведение при передаче None в качестве значения.
import json
class Lkdict(dict):
def __init__(self, d = {}) -> None:
for key,val in d.items():
if isinstance(val, dict):
val = self.__dict_to_self(val)
d[key] = val
return super().__init__(d)
def __dict_to_self(self, d: dict):
new_d = self.__class__()
for key,val in d.items():
if isinstance(val, dict):
val = self.__dict_to_self(val)
new_d[key] = val
return new_d
def __getitem__(self, keys):
if isinstance(keys, list):
d = self
for index,key in enumerate(keys):
if not isinstance(d, self.__class__):
raise KeyError(f'Key in list[{index}] not created. Check value dict with key in list[{index-1}]')
key in d or d.update(self.__class__({key: self.__class__()}))
d = d[key]
return d
return super().__getitem__(keys)
def __setitem__(self, keys, value) -> None:
if isinstance(value, dict):
value = self.__dict_to_self(value)
if isinstance(keys, list):
key = keys.pop()
d = self[keys]
if not isinstance(d, self.__class__):
raise KeyError(f'Key in list[{len(keys)}] not created. Check value dict with key in list[{len(keys)-1}]')
d[key] = value
return
return super().__setitem__(keys, value)
employe = Lkdict()
employe[['Vasya', 'documents', 'passport', 'id_number']] = 12345
employe[['Vasya', 'documents', 'ID_Card', 'id_number']] = 6789
employe[['Vasya', 'documents', 'ID_Card', 'id_number']] = 6
employe[['Vasya', 'documents', 'ID_Card', 'name']] = []
employe[['Vasya', 'documents', 'ID_Card', 'name']] = None
employe[['Andrey', 'skills']] = [1,2]
employe[['Andrey', 'skills']].append(4)
employe[['Vasya', 'documents', 'passport', 'id_number']]
employe[['Vasya', 'documents', 'ID_Card', 'id_number']]
employe[['Vasya', 'documents', 'ID_Card', 'id_number']]
employe[['Vasya', 'documents', 'ID_Card', 'id_number']]
employe[['Vasya', 'documents', 'ID_Card', 'name']]
print(json.dumps(employe, indent=1))
у меня код не работает, такое ошибка вылезает что сделать?
class d(dict):
def set(self, key, val=None):
if isinstance(key, list):
for i in key[:-1]:
self = self.set(i)
self[key[-1]] = val or self[key[-1]]
return self[key[-1]]
if val is None or isinstance(val, dict):
val = d()
self.get(key) or self.update(d({key: val}))
return self.get(key)
employe = d({'Andrey':d({'age': 31,
'profession': '',
'skills': [],
'documents':{}}),
})
#аналогично который сделал на верху
employe.set(['Vasya', 'documents', 'passport', 'id_number'], 12345)
#еше тесты
employe.set(['Vasya', 'documents', 'ID_Card', 'id_number'], 6789)
employe.set(['Vasya', 'documents', 'ID_Card', 'name'], 'Vasya')
employe.set(['Andrey', 'skills'], [1,2]).append(3)
employe.set(['Andrey', 'skills']).append(4)
print(json.dumps(employe, indent=1))
employe = {'Andrey':{'age': 31,
'profession': '',
'skills': [],
'documents':{}},
}
if employe.get('Vasya', {}).get('documents', {}).get('passport'):
employe['Vasya']['documents']['passport']['id_number'] = 12345
elif employe.get('Vasya', {}).get('documents'):
employe['Vasya']['documents']['passport'] = {'id_number': 12345}
elif employe.get('Vasya'):
employe['Vasya']['documents'] = {'passport': {'id_number': 12345}}
else:
employe['Vasya'] = {'documents': {'passport': {'id_number': 12345}}}
class d(dict):
def set(self, key, val=None):
if isinstance(key, list):
for i in key[:-1]:
self = self.set(i)
self[key[-1]] = val or self[key[-1]]
return self[key[-1]]
if val is None or isinstance(val, dict):
val = d()
self.get(key) or self.update(d({key: val}))
return self.get(key)
employe = d({'Andrey':d({'age': 31,
'profession': '',
'skills': [],
'documents':{}}),
})
#аналогично который сделал на верху
employe.set(['Vasya', 'documents', 'passport', 'id_number'], 12345)
#еше тесты
employe.set(['Vasya', 'documents', 'ID_Card', 'id_number'], 6789)
employe.set(['Vasya', 'documents', 'ID_Card', 'name'], 'Vasya')
employe.set(['Andrey', 'skills'], [1,2]).append(3)
employe.set(['Andrey', 'skills']).append(4)
print(json.dumps(employe, indent=1))
#для чтение
print(employe.set(['Vasya', 'documents', 'ID_Card', 'id_number']))
if (stepper.currentPosition() < targetPosition1)
Тут небольшая тонкость в терминологии, оптика была затянута как один кабель, но в данный момент это не кольцо, а отдельные аплинки между зданиями которые можно объединить в кольцо.да именно так.
Нужны не медиаконверторы, а L2 коммутаторы с минимум двумя SFP или SFP+ разъемами трансиверы под соответствуюшее волокно. И все в кольцо прекрастно собирается.