lst = [('a', 1), ('b', 2), ('c', 3)]
for k, v in lst: dic[k] = v
{k: v for k, v in lst}
if key not in dct: dct[key] = 0
dct[key] = dct.get(key, 0)
dic = {'Python': 1, 'Java': 2} new_dic = {} for k, v in dic.items(): new_dic[v] = k
dic = {'Python': 1, 'Java': 2} new_dic = {v: k for k, v in dic.items()}
lst = [('a', 1), ('b', 2), ('c', 3)] dic = {'a': [0]}
for key, value in lst: if key in dic: dic[key].append(value) else: dic[key] = [value]
for (key, value) in lst: group = dic.setdefault(key, []) group.append(value) # dic:{'a': [0, 1], 'b': [2], 'c': [3]}
dic1 = {'Python': 1, 'Java': 2, 'C': 3} dic2 = {'Python': 3, 'Java': 2, 'C++': 1} new_dic = {} for k, v in dic1.items(): if k in dic2.keys(): new_dic[k] = v print(new_dic) # {'Python': 1, 'Java': 2}
dic1 = {'Python': 1, 'Java': 2, 'C': 3} dic2 = {'Python': 3, 'Java': 2, 'C++': 1} print({k: dic1[k] for k in dic1.keys() & dic2.keys()}) # {'Python': 1, 'Java': 2}
dic1 = {'Python': 1, 'Java': 2, 'C': 3} dic2 = {'Python': 3, 'Java': 2, 'C++': 1} print(dic1.items() & dic2.items()) # {('Java', 2)}
dic = {'a': 2, 'b': 1, 'c': 3, 'd': 0} lst1 = sorted(dic.items(), key=lambda x: x[0], reverse=False) # [('a', 2), ('b', 1), ('c', 3), ('d', 0)] lst2 = sorted(dic.items(), key=lambda x: x[1], reverse=False) # [('d', 0), ('b', 1), ('a', 2), ('c', 3)] print('按照键降序:', {key: value for key, value in lst1}) print('按照值降序:', {key: value for key, value in lst2}) # 按照键降序: {'a': 2, 'b': 1, 'c': 3, 'd': 0} # 按照值降序: {'d': 0, 'b': 1, 'a': 2, 'c': 3}
dict_list = [ {'letter': 'B', 'number': '2'}, {'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '1'} ] # 按 letter 排序 print(sorted(dict_list, key=lambda dic: dic['letter'])) # 按 letter, number 排序 print(sorted(dict_list, key=lambda dic: (dic['letter'], dic['number']))) # [{'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '2'}, {'letter': 'B', 'number': '1'}] # [{'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '1'}, {'letter': 'B', 'number': '2'}]
from operator import itemgetter print(sorted(dict_list key=itemgetter('letter'))) print(sorted(dict_list, key=itemgetter('letter', 'number')))
以上がPython 辞書: やり方がわからない高度なゲームプレイはありますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。