更改python字典的字典键

jvlzgdj9  于 2022-12-25  发布在  Python
关注(0)|答案(4)|浏览(211)

我有这个字典

E['Will']={'Noun': 1/4, 'Modal': 3/4, 'Verb': 0}
E['Mary']={'Noun': 1, 'Modal': 0, 'Verb': 0}
E['Spot']={'Noun': 1/2, 'Modal': 0, 'Verb': 1/2}
E['Jane']={'Noun': 1, 'Modal': 0, 'Verb': 0}

我需要得到这个

emission_probability['Noun'] = {'Will': 1 / 4, 'Mary': 1, 'Spot': 1 / 2, 'Jane': 1}
emission_probability['Modal'] = {'Will': 3 / 4, 'Mary': 0, 'Spot': 0, 'Jane': 0}
emission_probability['Verb'] = {'Will': 0, 'Mary': 0, 'Spot': 1 / 2, 'Jane': 0}
emission_probability['End'] = {'Will': 0, 'Mary': 0, 'Spot': 0, 'Jane': 0}
62lalag4

62lalag41#

试试看:

E = {}
E["Will"] = {"Noun": 1 / 4, "Modal": 3 / 4, "Verb": 0}
E["Mary"] = {"Noun": 1, "Modal": 0, "Verb": 0}
E["Spot"] = {"Noun": 1 / 2, "Modal": 0, "Verb": 1 / 2}
E["Jane"] = {"Noun": 1, "Modal": 0, "Verb": 0}

out, all_keys = {}, ["Noun", "Modal", "Verb", "End"]

for k in all_keys:
    for kk, vv in E.items():
        out.setdefault(k, {})[kk] = E[kk].get(k, 0)

print(out)

图纸:

{
    "Noun": {"Will": 0.25, "Mary": 1, "Spot": 0.5, "Jane": 1},
    "Modal": {"Will": 0.75, "Mary": 0, "Spot": 0, "Jane": 0},
    "Verb": {"Will": 0, "Mary": 0, "Spot": 0.5, "Jane": 0},
    "End": {"Will": 0, "Mary": 0, "Spot": 0, "Jane": 0},
}
scyqe7ek

scyqe7ek2#

from collections import defaultdict
emission_probability = defaultdict(dict)
for k, v in E.items():
    emission_probability['End'][k] = 0
    for k2, v2 in v.items():
        emission_probability[k2][k] = v2
print(dict(emission_probability))
sqserrrh

sqserrrh3#

如果你习惯了Pandas,把它扔到pd.DataFrame里真的很容易。

pd.DataFrame(E).transpose().to_dict()

df = pd.DataFrame(E)创建以下内容:

Will  Mary  Spot  Jane
Noun  0.25     1   0.5     1
Modal 0.75     0   0.0     0
Verb  0.00  0.00   0.5     0

然后,df.transpose()将生成:

Noun  Modal  Verb
Will  0.25   0.75   0.0
Mary  1.00   0.00   0.0
Spot  0.50   0.00   0.5
Jane  1.00   0.00   0.0

如果你真的想把它放回字典里,你可以调用df.to_dict(),得到:

{'Noun': {'Will': 0.25, 'Mary': 1.0, 'Spot': 0.5, 'Jane': 1.0}, 
'Modal': {'Will': 0.75, 'Mary': 0.0, 'Spot': 0.0, 'Jane': 0.0}, 
'Verb': {'Will': 0.0, 'Mary': 0.0, 'Spot': 0.5, 'Jane': 0.0}}

坦率地说,我只会把它转换成一个 Dataframe ,并以这种方式使用它。

ryevplcw

ryevplcw4#

emission_probability = {}

for word, word_dict in E.items():
    for pos, prob in word_dict.items():
        if pos not in emission_probability:
            emission_probability[pos] = {}
        emission_probability[pos][word] = prob

# Add an entry for the "End" position
for word in E:
    if "End" not in emission_probability:
        emission_probability["End"] = {}
    emission_probability["End"][word] = 0

相关问题