猿问

如何使用先前字典中的键和值创建字典?

我需要创建一个字典,其键是来自先前创建的字典的值。我以前的字典是:


{100000: (400, 'Does not want to build a %SnowMan %StopAsking', ['SnowMan', 'StopAsking'], [100, 200, 300], [400, 500]), 

100001: (200, 'Make the ocean great again.', [''], [], [400]), 

100002: (500, "Help I'm being held captive by a beast!  %OhNoes", ['OhNoes'], [400], [100, 200, 300]), 

100003: (500, "Actually nm. This isn't so bad lolz :P %StockholmeSyndrome", ['StockholmeSyndrome'], [400, 100], []), 

100004: (300, 'If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.', ['ShowYouTheWorld', 'JustSayNo'], [500, 200], [400]), 

100005: (400, 'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan', ['StockholmeSyndrome', 'SnowMan'], [], [200, 300, 100, 500])}

这个字典的形式是 {key: (id, string, tags, likes, dislikes)} 我需要创建一个字典,它的键是第一个字典中的标签,它的值是包含标签,以字典的形式呈现。


例如,如果我们使用 tag 'SnowMan',新字典应该是这样的:


{'SnowMan': {400: ['Does not want to build a %SnowMan %StopAsking', 'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']}}

或者,如果我们使用 tag 'StockholmeSyndrome',新字典应该是这样的:


{'StockholmeSyndrome': {

        500: ["Actually nm. This isn't so bad lolz :P %StockholmeSyndrome"], 

        400: ['LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']}}

最后,新字典需要将之前字典中的所有标签都包含为键,包括没有标签的事件。


我真的被困在这个问题上,有人可以提供一些指导吗?


明月笑刀无情
浏览 163回答 3
3回答

冉冉说

使用collections.defualtdict您可以迭代并附加到嵌套字典结构中的列表:from collections import defaultdictdd = defaultdict(lambda: defaultdict(list))for id_, text, tags, likes, dislikes in d.values():&nbsp; &nbsp; for tag in tags:&nbsp; &nbsp; &nbsp; &nbsp; dd[tag][id_].append(text)print(dd)defaultdict(<function __main__.<lambda>>,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {'': defaultdict(list, {200: ['Make the ocean great again.']}),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'JustSayNo': defaultdict(list,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']}),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'OhNoes': defaultdict(list,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{500: ["Help I'm being held captive by a beast!&nbsp; %OhNoes"]}),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'ShowYouTheWorld': defaultdict(list,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']}),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'SnowMan': defaultdict(list,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{400: ['Does not want to build a %SnowMan %StopAsking',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'LOLZ BELLE.&nbsp; %StockholmeSyndrome&nbsp; %SnowMan']}),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'StockholmeSyndrome': defaultdict(list,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{400: ['LOLZ BELLE.&nbsp; %StockholmeSyndrome&nbsp; %SnowMan'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 500: ["Actually nm. This isn't so bad lolz :P %StockholmeSyndrome"]}),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'StopAsking': defaultdict(list,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{400: ['Does not want to build a %SnowMan %StopAsking']})})defaultdict是 的子类dict,因此您通常不需要进一步操作。但是,如果您需要常规dict对象,则可以使用递归函数:def default_to_regular_dict(d):&nbsp; &nbsp; """Convert nested defaultdict to regular dict of dicts."""&nbsp; &nbsp; if isinstance(d, defaultdict):&nbsp; &nbsp; &nbsp; &nbsp; d = {k: default_to_regular_dict(v) for k, v in d.items()}&nbsp; &nbsp; return dres = default_to_regular_dict(dd)print(res){'': {200: ['Make the ocean great again.']},&nbsp;'JustSayNo': {300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']},&nbsp;'OhNoes': {500: ["Help I'm being held captive by a beast!&nbsp; %OhNoes"]},&nbsp;'ShowYouTheWorld': {300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']},&nbsp;'SnowMan': {400: ['Does not want to build a %SnowMan %StopAsking',&nbsp; &nbsp;'LOLZ BELLE.&nbsp; %StockholmeSyndrome&nbsp; %SnowMan']},&nbsp;'StockholmeSyndrome': {400: ['LOLZ BELLE.&nbsp; %StockholmeSyndrome&nbsp; %SnowMan'],&nbsp; 500: ["Actually nm. This isn't so bad lolz :P %StockholmeSyndrome"]},&nbsp;'StopAsking': {400: ['Does not want to build a %SnowMan %StopAsking']}}

繁星淼淼

那这个呢 ?keys = ['name', 'last_name', 'phone_number', 'email']dict2 = {x:dict1[x] for x in keys}

海绵宝宝撒

在查看了您的要求后,我已使用以下代码更新了我之前的帖子。我相信这就是您正在努力实现的目标。唯一需要的导入是来自 collections 模块的OrderedDict。from collections import OrderedDictfrom pprint import PrettyPrinter as ppstr_tag_dict = {}for v in d.values():&nbsp; &nbsp; str_tag_dict[v[1]] = v[2]def same_tags_and_ids(str1, str2):&nbsp; &nbsp; dd = {str1:str_tag_dict[str1],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str2:str_tag_dict[str2]}&nbsp; &nbsp; tag = []&nbsp; &nbsp; v = dd[str1]&nbsp; &nbsp; for vv in v:&nbsp; &nbsp; &nbsp; &nbsp; for ks in dd.keys():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if vv in dd[ks]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tag.append(vv)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for tg in tag:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if tag.count(tg) > 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return tg&nbsp; &nbsp; return Noneordp = OrderedDict(sorted(d.items()))def same_tags_diff_ids():&nbsp; &nbsp; x = []&nbsp; &nbsp; y = []&nbsp; &nbsp; my_str = []&nbsp; &nbsp; for v in ordp.values():&nbsp; &nbsp; &nbsp; &nbsp; x.append(v[2][0])&nbsp; &nbsp; &nbsp; &nbsp; x.append(v[0])&nbsp; &nbsp; &nbsp; &nbsp; x.append(v[1])&nbsp; &nbsp; &nbsp; &nbsp; for i in x:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if x.count(i) > 1 and type(i) == str:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; y.append(i)&nbsp; &nbsp; for i in range(len(x)):&nbsp; &nbsp; &nbsp; &nbsp; if x[i] == list(set(y))[0]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; my_str.append({list(set(y))[0]:{x[i + 1]:[x[i + 2]]}})&nbsp; &nbsp; d={}&nbsp; &nbsp; k1, v1 = list(my_str[0][list(my_str[0])[0]].items())[0]&nbsp; &nbsp; k2, v2 = list(my_str[1][list(my_str[1])[0]].items())[0]&nbsp; &nbsp; d.update({list(my_str[0].keys())[0]:{k1:v1, k2:v2}})&nbsp;&nbsp; &nbsp; if not d == None:&nbsp; &nbsp; &nbsp; &nbsp; return d&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return Nonedup_tag_str = same_tags_diff_ids()for k, v in ordp.items():&nbsp; &nbsp; del d[k]&nbsp; &nbsp; for tag in v[2]:&nbsp; &nbsp; &nbsp; &nbsp; d[tag] = {v[0]:[v[1]]}ordp = OrderedDict(sorted(d.items()))ids= [list(v.keys())[0] for v in ordp.values()]strs= [list(v.values())[0][0] for v in ordp.values()]x = 0for n in range(len(ordp)):&nbsp; &nbsp; tmp_keys = []&nbsp; &nbsp; for k, v in ordp.items():&nbsp; &nbsp; &nbsp; &nbsp; if not strs[x] == list(v.values())[0][0]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ids[x] == list(v.keys())[0]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; key = same_tags_and_ids(strs[x], list(v.values())[0][0])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not key == None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp_keys.append(key)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if tmp_keys.count(key) == 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ordp[key][list(v.keys())[0]].append(strs[x])&nbsp; &nbsp; x += 1dx = dup_tag_strdy = dict(ordp)dy.update(dx)pp().pprint(dy)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;输出:&nbsp;{'': {200: ['Make the ocean great again.']},&nbsp;'JustSayNo': {300: ['If some random dude offers to %ShowYouTheWorld do '&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'yourself a favour and %JustSayNo.']},&nbsp;'OhNoes': {500: ["Help I'm being held captive by a beast!&nbsp; %OhNoes"]},&nbsp;'ShowYouTheWorld': {300: ['If some random dude offers to %ShowYouTheWorld&nbsp;&nbsp; do yourself a favour and %JustSayNo.']},&nbsp;'SnowMan': {400: ['LOLZ BELLE.&nbsp; %StockholmeSyndrome&nbsp; %SnowMan',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;'Does not want to build a %SnowMan %StopAsking']},&nbsp;'StockholmeSyndrome': {400: ['LOLZ BELLE.&nbsp; %StockholmeSyndrome %SnowMan'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 500: ["Actually nm. This isn't so bad lolz :P "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '%StockholmeSyndrome']},&nbsp;'StopAsking': {400: ['Does not want to build a %SnowMan %StopAsking']}}
随时随地看视频慕课网APP

相关分类

Python
我要回答