Python根据字典

时间:2018-03-06 19:43:39

标签: python dictionary

A = {0:{a:1, b:7}, 1:{a:5,b:5}, 2:{a:4,b:6}}

我想根据每个子词典中所有guess的值b会计,将项b's附加到每个子词典。

在词典A中说:

0-b-7 percentage of b:  7/(7+5+6)
1-b-5 percentage of b:  5/(7+5+6)
2-b-6 percentage of b:  1 - 7/(7+5+6) - 5/(7+5+6)

所需的词典应该像

A = {0:{a:1, b:7, 'guess': 7/(7+5+6)}, 
     1:{a:5,b:5, 'guess':  5/(7+5+6)}, 
     2:{a:4,b:6, 'guess':  1 - 7/(7+5+6) - 5/(7+5+6)}}

我不知道如何将其他两个b's合并到特定的子字典中。

4 个答案:

答案 0 :(得分:1)

A = {0:{"a":1, "b":7}, 1:{"a":5,"b":5}, 2:{"a":4,"b":6}}

char = "b"
denominator = 0

# =========================
# First Calculate the sum 
# =========================
for key in A:
  inner_map = A[key]
  denominator += inner_map[char]

# ========================================
# Now insert the new key to the inner_map
# ========================================
for key in A:
  inner_map = A[key]
  inner_map["guess"] = inner_map[char]/denominator

print(A)
  • 输出:

    {0: {'a': 1, 'b': 7, 'guess': 0.3888888888888889}, 1: {'a': 5, 'b': 5, 'guess': 0.2777777777777778}, 2: {'a': 4, 'b': 6, 'guess': 0.3333333333333333}}
    

答案 1 :(得分:1)

一种方法是预先计算所有b的总和,然后使用它为字典添加新的键值对。

b_total = float(sum(A[k]['b'] for k in A))
for k in A:
    A[k]['guess'] = A[k]['b'] / b_total

#{0: {'a': 1, 'b': 7, 'guess': 0.3888888888888889},
# 1: {'a': 5, 'b': 5, 'guess': 0.2777777777777778},
# 2: {'a': 4, 'b': 6, 'guess': 0.3333333333333333}}

答案 2 :(得分:0)

试试这个:

def add_calc(my_dict):
    total_guesses = sum(map(lambda x: my_dict.get(x).get('b'), my_dict))
    for item in my_dict.itervalues():
        item.update({'guess': 1.0 * item.get('b') / total_guesses})
    return my_dict

d = add_calc(A)

{0: {'a': 1, 'b': 7, 'guess': 0.3888888888888889},
 1: {'a': 5, 'b': 5, 'guess': 0.2777777777777778},
 2: {'a': 4, 'b': 6, 'guess': 0.3333333333333333}}

我使用的是Python 2 btw,你没有指定版本

答案 3 :(得分:0)

您可以使用字典解包:

import matplotlib.pyplot as plt
import numpy as np


fig, (ax1,ax2) = plt.subplots(ncols=2, sharey=True, 
                              subplot_kw=dict(aspect='equal'),
                              gridspec_kw=dict(width_ratios=[6,1]))

def create_data(xmin,xmax):
    delta = 0.025

    x = np.arange(xmin, xmax, delta)
    y = np.arange(-3,3,delta)
    X, Y = np.meshgrid(x, y)
    Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
    Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
    Z = 10 * (Z1 - Z2)

    nr, nc = Z.shape

    # put NaNs in one corner:
    Z[-nr//6:, -nc//6:] = np.nan
    # contourf will convert these to masked


    Z = np.ma.array(Z)
    # mask another corner:
    Z[:nr//6, :nc//6] = np.ma.masked

    # mask a circle in the middle:
    interior = np.sqrt((X**2) + (Y**2)) < 0.5
    Z[interior] = np.ma.masked
    return X,Y,Z

X,Y,Z=create_data(-2,4)
ax1.contourf(X,Y,Z)
ax1.set_ylim(-1,1)
ax1.set_xlim(-2,4)
X,Y,Z=create_data(-1,0)
ax2.contourf(X,Y,Z)
ax2.set_ylim(-1,1)
ax2.set_xlim(-1,0)
plt.show()

输出:

A = {0:{'a':1, 'b':7}, 1:{'a':5, 'b':5}, 2:{'a':4, 'b':6}}
results = {a:{**b, **{'guess':b['b']/float(sum(c['b'] for _, c in A.items()))}} for a, b in A.items()}