2017-08-30 171 views
-1

我有以下列表。我想創建一個字典,其中第一個列表的值爲key,第二個爲值。像將列表轉換爲Python中列表的字典

mydict = {22:1 0 0 0, 23:0 1 2 1} 

mydata =[(22, 1), 
      (22, 0), 
      (22, 0), 
      (22, 1), 
      (23, 0), 
      (23, 1), 
      (23, 2), 
      (23, 1), 
      (23, 0), 
      (24, 3), 
      (24, 3), 
      (24, 2), 
      (24, 1), 
      (24, 0)] 
+0

什麼類型的F值做你想做'0 0 0 1'是一個字符串? – Vladyslav

+1

正確地格式化您的問題,以便我們可以看到數據類型 – RomanPerekhrest

+0

0 0 0 1這些是整數。 –

回答

0

東西,你可以通過如下因素代碼做到這一點

for i in mydata: 
    if mydict.get(i[0], ''): 
     mydict[i[0]] += ' ' + str(i[1]) 
    else: 
     mydict[i[0]] = str(i[1]) 

print(mydict) 
{'22': "1 0 0 0", '23':"0 1 2 1"} 

這是如果你的字典值 - 串

2

您應該能夠利用數據結構爲collections.defaultdict

import collections 

l = [(22, 1), 
(22, 0), 
(22, 0), 
(22, 1), 
(23, 0), 
(23, 1), 
(23, 2), 
(23, 1), 
(23, 0), 
(24, 3), 
(24, 3), 
(24, 2), 
(24, 1), 
(24, 0)] 

d = collections.defaultdict(list) 
for x, y in l: 
    d[x].append(y) 

print(dict(d)) 
{22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]} 

有使用dict.setdefault替代,但它是稍微低效率。

d = {} 
for x, y in l: 
    d.setdefault(x, []).append(y) 

print(d) 
{22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]} 

如果你希望他們爲空格分隔字符串,你需要邏輯的第二層使用的字典補償和str.join

out = {k : ' '.join(map(str, v)) for k, v in d.items()} 
print(out) 
{22: '1 0 0 1', 23: '0 1 2 1 0', 24: '3 3 2 1 0'} 
+0

謝謝你的幫助 –

0

隨着itertools.groupby()功能:

import itertools 

data = [(22,1), (22,0), (22,0), (22,1), (23,0), (23,1), (23,2), (23,1), (23,0), (24,3), (24,3), (24,2), (24,1), (24,0)] 
result = {k: list(i[1] for i in g) 
      for k,g in itertools.groupby(sorted(data), key=lambda x: x[0])} 
print(result) 

輸出:

{24: [0, 1, 2, 3, 3], 22: [0, 0, 1, 1], 23: [0, 0, 1, 1, 2]} 
0

一個簡單的for循環:

mydict = {} 

for i in range(len(mydata)): 
    mylist = mydict.get(mydata[i][0], []) 
    mylist.append(mydata[i][1]) 
    mydict[mydata[i][0]] = mylist