为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

明月笑刀无情 2021-09-02 15:39:51
我需要创建一个字典,其键是来自先前创建的字典的值。我以前的字典是:{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']}}最后,新字典需要将之前字典中的所有标签都包含为键,包括没有标签的事件。我真的被困在这个问题上,有人可以提供一些指导吗?
查看完整描述

3 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

使用collections.defualtdict您可以迭代并附加到嵌套字典结构中的列表:


from collections import defaultdict


dd = defaultdict(lambda: defaultdict(list))

for id_, text, tags, likes, dislikes in d.values():

    for tag in tags:

        dd[tag][id_].append(text)


print(dd)


defaultdict(<function __main__.<lambda>>,

            {'': defaultdict(list, {200: ['Make the ocean great again.']}),

             'JustSayNo': defaultdict(list,

                         {300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']}),

             'OhNoes': defaultdict(list,

                         {500: ["Help I'm being held captive by a beast!  %OhNoes"]}),

             'ShowYouTheWorld': defaultdict(list,

                         {300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']}),

             'SnowMan': defaultdict(list,

                         {400: ['Does not want to build a %SnowMan %StopAsking',

                           'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']}),

             'StockholmeSyndrome': defaultdict(list,

                         {400: ['LOLZ BELLE.  %StockholmeSyndrome  %SnowMan'],

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

             'StopAsking': defaultdict(list,

                         {400: ['Does not want to build a %SnowMan %StopAsking']})})

defaultdict是 的子类dict,因此您通常不需要进一步操作。但是,如果您需要常规dict对象,则可以使用递归函数:


def default_to_regular_dict(d):

    """Convert nested defaultdict to regular dict of dicts."""

    if isinstance(d, defaultdict):

        d = {k: default_to_regular_dict(v) for k, v in d.items()}

    return d


res = default_to_regular_dict(dd)


print(res)


{'': {200: ['Make the ocean great again.']},

 'JustSayNo': {300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']},

 'OhNoes': {500: ["Help I'm being held captive by a beast!  %OhNoes"]},

 'ShowYouTheWorld': {300: ['If some random dude offers to %ShowYouTheWorld do yourself a favour and %JustSayNo.']},

 'SnowMan': {400: ['Does not want to build a %SnowMan %StopAsking',

   'LOLZ BELLE.  %StockholmeSyndrome  %SnowMan']},

 'StockholmeSyndrome': {400: ['LOLZ BELLE.  %StockholmeSyndrome  %SnowMan'],

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

 'StopAsking': {400: ['Does not want to build a %SnowMan %StopAsking']}}


查看完整回答
反对 回复 2021-09-02
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

那这个呢 ?


keys = ['name', 'last_name', 'phone_number', 'email']

dict2 = {x:dict1[x] for x in keys}


查看完整回答
反对 回复 2021-09-02
?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

在查看了您的要求后,我已使用以下代码更新了我之前的帖子。我相信这就是您正在努力实现的目标。唯一需要的导入是来自 collections 模块的OrderedDict。


from collections import OrderedDict

from pprint import PrettyPrinter as pp



str_tag_dict = {}

for v in d.values():

    str_tag_dict[v[1]] = v[2]


def same_tags_and_ids(str1, str2):

    dd = {str1:str_tag_dict[str1], 

          str2:str_tag_dict[str2]}

    tag = []

    v = dd[str1]

    for vv in v:

        for ks in dd.keys():

            if vv in dd[ks]:

                tag.append(vv)

                for tg in tag:

                    if tag.count(tg) > 1:

                        return tg

    return None


ordp = OrderedDict(sorted(d.items()))

def same_tags_diff_ids():

    x = []

    y = []

    my_str = []

    for v in ordp.values():

        x.append(v[2][0])

        x.append(v[0])

        x.append(v[1])

        for i in x:

            if x.count(i) > 1 and type(i) == str:

                y.append(i)

    for i in range(len(x)):

        if x[i] == list(set(y))[0]:

            my_str.append({list(set(y))[0]:{x[i + 1]:[x[i + 2]]}})

    d={}

    k1, v1 = list(my_str[0][list(my_str[0])[0]].items())[0]

    k2, v2 = list(my_str[1][list(my_str[1])[0]].items())[0]

    d.update({list(my_str[0].keys())[0]:{k1:v1, k2:v2}}) 

    if not d == None:

        return d

    else:

        return None

dup_tag_str = same_tags_diff_ids()


for k, v in ordp.items():

    del d[k]

    for tag in v[2]:

        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 = 0

for n in range(len(ordp)):

    tmp_keys = []

    for k, v in ordp.items():

        if not strs[x] == list(v.values())[0][0]:

            if ids[x] == list(v.keys())[0]:

                key = same_tags_and_ids(strs[x], list(v.values())[0][0])

                if not key == None:

                    tmp_keys.append(key)

                    if tmp_keys.count(key) == 1:

                        continue

                    else:

                        ordp[key][list(v.keys())[0]].append(strs[x])

    x += 1

dx = dup_tag_str

dy = dict(ordp)

dy.update(dx)

pp().pprint(dy)               

输出:


 {'': {200: ['Make the ocean great again.']},

 'JustSayNo': {300: ['If some random dude offers to %ShowYouTheWorld do '

                 'yourself a favour and %JustSayNo.']},

 'OhNoes': {500: ["Help I'm being held captive by a beast!  %OhNoes"]},

 'ShowYouTheWorld': {300: ['If some random dude offers to %ShowYouTheWorld 

  do yourself a favour and %JustSayNo.']},

 'SnowMan': {400: ['LOLZ BELLE.  %StockholmeSyndrome  %SnowMan',

               'Does not want to build a %SnowMan %StopAsking']},

 'StockholmeSyndrome': {400: ['LOLZ BELLE.  %StockholmeSyndrome %SnowMan'],

                        500: ["Actually nm. This isn't so bad lolz :P "

                          '%StockholmeSyndrome']},

 'StopAsking': {400: ['Does not want to build a %SnowMan %StopAsking']}}


查看完整回答
反对 回复 2021-09-02
  • 3 回答
  • 0 关注
  • 162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信