Home > database >  Change the dictionary key of python dictionaries
Change the dictionary key of python dictionaries

Time:12-24

I have this Dict

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}

I need to obtain this

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}

CodePudding user response:

Try:

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)

Prints:

{
    "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},
}

CodePudding user response:

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))

CodePudding user response:

```python

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

CodePudding user response:

If you're used to pandas, it would be really easy to throw it into a pd.DataFrame.

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

df = pd.DataFrame(E) creates this:

      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

Then, df.transpose() yields this:

      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

If you really want it back into a dictionary, you could just call df.to_dict(), which yields:

{'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}}

Frankly, I would just convert it to a dataframe and use it that way.

  • Related