从2D阵列Python制作字典? [英] Make Dictionary from 2D Array Python?

查看:50
本文介绍了从2D阵列Python制作字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D数组,如下所示.

I have a 2D array as follows.

[['FE0456143', '218.04'], ['FB1357448', '217.52'], ['FB1482960', '222.70'], ['FB1483107', '223.32'], ['FE0456556', '12429.67'], ['FE0456594', '213.71'], ['FB1483056', '218.86'], ['FE0456061', '12392.33'], ['FB1482479', '223.35']]

第一个元素是键,第二个元素是值.我尝试过:

The first element is the key while the second is the value. I have tried:

keys = zip(*data)[0]
vals = zip(*data)[1]
dic(zip(keys,vals)) 

但是,数组中的某些元素可能具有重复的键,而这些元素不对应于它们?我希望所有键都具有3个与之关联的值?

However some elements of the array may have duplicate keys, and the elements are not corresponding to them? I want all of the keys to have 3 values associated with it?

推荐答案

听起来像您想要 1对多的映射.如果您将值设为列表:

Sounds like you want a 1 to many mapping. You can have this if you make your value a list:

from collections import defaultdict

d = defaultdict(list)

for k, v in data:
    d[k].append(v)

这篇关于从2D阵列Python制作字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆