#python #dictionary
#python #словарь
Вопрос:
Вот мой словарь dict_1:
{'ABC1': None, 'BBC2': None, 'PPP13': None, '1FGEE':None, 'STUFF':None, 'LUB23':None, 'UNIT44':None, 'ZX3454F2':None, 'AMS76':None, 'LLPT43':None}
Я пытаюсь заменить значения строками в списке:
list_info:
['ABC1-99.txt', 'BBC2-qp.txt', 'PPP13-jj5.txt', 'PPP13-frr.txt', '1FGEE-oop2.txt', 'STUFF-34534.txt', 'LUB23-j873.txt', 'UNIT44-oi5.txt', 'ZX3454F2-k.txt', UNIT44-de3t.txt, 'AMS76-light.txt', 'LLPT43-ifg.txt']
Желаемый результат:
{'ABC1':['ABC1-99.txt'], 'BBC2':['BBC2-qp.txt'], 'PPP13':['PPP13-jj5.txt', 'PPP13-frr.txt'],
'1FGEE':['1FGEE-oop2.txt'], 'UNIT44':['UNIT44-oi5.txt','UNIT44-de3t.txt'], ...}
Я проверил это с помощью кода:
new_dict = dict((i,j) for i,j in dict_1.items() if j in [n.split('-', 1)[0] for n in list_info])
все еще не могу понять это правильно
🙂
Ответ №1:
Вы можете создать новый dict с теми же ключами, что и dict_1. и каждое значение представляет собой список, содержащий все имена файлов, которые начинаются с ключа.
dict_1 = {'ABC1': None, 'BBC2': None, 'PPP13': None, '1FGEE':None, 'STUFF':None, 'LUB23':None, 'UNIT44':None, 'ZX3454F2':None, 'AMS76':None, 'LLPT43':None}
list_info = ['ABC1-99.txt', 'BBC2-qp.txt', 'PPP13-jj5.txt', 'PPP13-frr.txt', '1FGEE-oop2.txt', 'STUFF-34534.txt', 'LUB23-j873.txt', 'UNIT44-oi5.txt', 'ZX3454F2-k.txt', 'UNIT44-de3t.txt', 'AMS76-light.txt', 'LLPT43-ifg.txt']
new_dict = {k: [fname for fname in list_info if fname.startswith(k)] for k in dict_1}
print(new_dict)
# if you need to modify dict_1 in place
dict_1.update(new_dict)
{'ABC1': ['ABC1-99.txt'], 'BBC2': ['BBC2-qp.txt'], 'PPP13': ['PPP13-jj5.txt', 'PPP13-frr.txt'], '1FGEE': ['1FGEE-oop2.txt'], 'STUFF': ['STUFF-34534.txt'], 'LUB23': ['LUB23-j873.txt'], 'UNIT44': ['UNIT44-oi5.txt', 'UNIT44-de3t.txt'], 'ZX3454F2': ['ZX3454F2-k.txt'], 'AMS76': ['AMS76-light.txt'], 'LLPT43': ['LLPT43-ifg.txt']}
Ответ №2:
d = {}
for s in list_info:
key = s.split('-')[0]
d.setdefault(key, []).append(s)
Поскольку d
у вас есть нужные данные, вам на самом деле не нужны значения dict_1
со None
значениями, но вы можете обновить их с помощью нового словаря, если хотите:
dict_1.update(d)
Ответ №3:
Я думаю, это должно сработать.
dictionary = {'ABC1': None, 'BBC2': None, 'PPP13': None, '1FGEE':None, 'STUFF':None, 'LUB23':None, 'UNIT44':None, 'ZX3454F2':None, 'AMS76':None, 'LLPT43':None}
txtlist = ['ABC1-99.txt', 'BBC2-qp.txt', 'PPP13-jj5.txt', 'PPP13-frr.txt', '1FGEE-oop2.txt', 'STUFF-34534.txt', 'LUB23-j873.txt', 'UNIT44-oi5.txt', 'ZX3454F2-k.txt', 'UNIT44-de3t.txt', 'AMS76-light.txt', 'LLPT43-ifg.txt']
res = list(dictionary.keys())
for i in range(len(res)):
dictionary[res[i]] = txtlist[i]
print(dictionary)