在循环中创建字典

时间:2018-06-12 15:52:48

标签: python-2.7 dictionary

我有2个列表,我想将它们转换为带有键和值的dict。我设法做到了,但步骤太多,所以我想知道是否有更简单的方法来实现这一点。基本上我想在循环中直接创建dict而不需要额外的步骤。我刚开始使用python,我不太了解它提供的所有数据类型。 如果需要,可以修改jName表单。

jName=["Nose", "Neck", "RShoulder", "RElbow", "RWrist", "LShoulder", "LElbow", "LWrist", "RHip",
        "RKnee","RAnkle","LHip", "LKnee", "LAnkle", "REye", "LEye", "REar", "LEar"]
def get_joints(subset, candidate):
    joints_per_skeleton = [[] for i in range(len(subset))]
    # for each detected skeleton
    for n in range(len(subset)):
        # for each joint
        for i in range(18):
            cidx = subset[n][i]
            if cidx != -1:
                y = candidate[cidx.astype(int), 0]
                x = candidate[cidx.astype(int), 1]
                joints_per_skeleton[n].append((y, x))
            else:
                joints_per_skeleton[n].append(None)
    return joints_per_skeleton

joints = get_joints(subset,candidate)
print joints

这是列表

的关节列表的输出
[[None, (48.0, 52.0), (72.0, 50.0), None, None, (24.0, 55.0), (5.0, 105.0), None, (63.0, 159.0), (57.0, 221.0), (55.0, 281.0), (28.0, 154.0), (23.0, 219.0), (23.0, 285.0), None, (25.0, 17.0), (55.0, 18.0), (30.0, 21.0)]]

这里我定义了一个从2个列表中创建字典的函数

def create_dict(keys, values):
    return dict(zip(keys, values))

my_dict = create_dict(jointsName, joints[0])

结果如下:

{'LAnkle': (23.0, 285.0),
 'LEar': (30.0, 21.0),
 'LElbow': (5.0, 105.0),
 'LEye': (25.0, 17.0),
 'LHip': (28.0, 154.0),
 'LKnee': (23.0, 219.0),
 'LShoulder': (24.0, 55.0),
 'LWrist': None,
 'Neck': (48.0, 52.0),
 'Nose': None,
 'RAnkle': (55.0, 281.0),
 'REar': (55.0, 18.0),
 'RElbow': None,
 'REye': None,
 'RHip': (63.0, 159.0),
 'RKnee': (57.0, 221.0),
 'RShoulder': (72.0, 50.0),
 'RWrist': None}

1 个答案:

答案 0 :(得分:1)

我认为defaultdict可以帮到你。我做了我自己的例子来表明你可以预先定义键然后通过双循环,并且dict的值是可能不同大小的列表。如果这回答了你的问题,请告诉我:

from collections import defaultdict
import random
joint_names = ['hip','knee','wrist']
num_skeletons = 10

d = defaultdict(list)

for skeleton in range(num_skeletons):
    for joint_name in joint_names:
        r1 = random.randint(0,10)
        r2 = random.randint(0,10)
        if r1 > 4:
            d[joint_name].append(r1*r2)

print d

输出:

defaultdict(<type 'list'>, {'hip': [0, 5, 30, 36, 56], 'knee': [35, 50, 10], 'wrist': [27, 5, 15, 64, 30]})

作为一个说明,我发现很难阅读您的代码,因为在您发布的代码段之前已经定义了一些变量。