LoginSignup
9
10

More than 5 years have passed since last update.

python / リストからdictを作る。

Last updated at Posted at 2014-12-22

はじめに

リストからDictを作る。個人的によく使う、numpyのloadtxtを使うので、numpy_arrray型ですが、別にlist型でも問題無く使える。
{"hoge":(hoge1,hoge2,hoge3,…}といった辞書型を作れる。

(備忘録)

  1. 適当に配列を作る。ここでは、a,b,cとする。
    • aをkey、bおよびcを値とする。
  2. まずzip()で、bおよびcをtupleにする。(_bcとする)
  3. その後、dict()で、aと_bcをくっつける。
list2dict.py
import numpy as np
a,b,c = np.arange(10), np.arange(10)*2, np.arange(10)*3

#-> a: [0 1 2 3 4 5 6 7 8 9]
#-> b: [ 0  2  4  6  8 10 12 14 16 18]
#-> c: [ 0  3  6  9 12 15 18 21 24 27]

_bc = zip(b,c)

result = dict(zip(a,_bc))
#-> {0: (0, 0), 1: (2, 3), 2: (4, 6), 3: (6, 9), 4: (8, 12), 5: (10, 15), 6: (12, 18), 7: (14, 21), 8: (16, 24), 9: (18, 27)}

# result = dict(zip(a,zip(b,c)))でもイイ。

おしまい。

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10