2013-03-13 73 views
2

從db我得到的數據如下。然後,我正在根據這些數據準備一個Python字典。現在我想爲每一行分配一個顏色,但是有一個條件。如果一個codezone與多個拉鍊相關聯,則該行將變爲灰色。與單拉鍊相關的區域會得到一些其他顏色。我如何從下面的數據準備字典。根據django字典中的數據計數分配顏色

+----------+-------+--------------+ 
| codeZone | ZipCd | Longitude | 
+----------+-------+--------------+ 
| Zone 81 | 13064 | -76.70275100 | 
| Zone 81 | 13143 | -76.73114800 | 
| Zone 81 | 13146 | -76.76016600 | 
| Zone 72 | 13148 | -76.78488000 | 
| Zone 72 | 13165 | -76.87704600 | 
| Zone 50 | 14011 | -78.28090700 | 
| Zone 50 | 14020 | -78.19062500 | 
| Zone 50 | 14058 | -78.15694600 | 
| Zone 50 | 14098 | -78.37735300 | 
| Zone 50 | 14103 | -78.38546900 | 
| Zone 50 | 14125 | -78.27249300 | 
| Zone 50 | 14143 | -78.08089700 | 
| Zone 50 | 14411 | -78.20223900 | 
| Zone 81 | 14413 | -76.98321400 | 
| Zone 60 | 14414 | -77.73609300 | 
| Zone 50 | 14416 | -77.98543200 | 
| Zone 72 | 14418 | -77.21132300 | 
| Zone 14 | 14420 | -77.92950200 | 
| Zone 50 | 14422 | -78.07160700 | 
| Zone 60 | 14423 | -77.84307800 | 
| Zone 71 | 14424 | -77.30122500 | 
| Zone 70 | 14425 | -77.31024000 | 
| Zone 61 | 14427 | -78.04682800 | 
| Zone 16 | 14428 | -77.81500000 | 
+----------+-------+--------------+ 

我的數據看起來是likr這

[{ '區域':1, '拉鍊':1, '規範':一},{ '區域':1, '拉鍊':2 ,'spec':m},{'zone':2,'zip':3,'spec':pC}]

現在區域1與zip 1和zip 2關聯。區域2僅與zip 3.所以我想要第四個鍵(即顏色)的dictioanry,這將基於區域的計數(如果多於一個區域,然後灰色)。所以對於拉鍊1和拉鍊2,顏色將是灰色的。對於zip 3任何其他顏色。

回答

2

計數每個區域的郵政編碼,然後在您的映射信息:。

from collections import defaultdict 

zipcount = defaultdict(set) 
for zone, zip, longitude in datarows: 
    zipcount[zone].add(zip) 

# Create the output dictionary 
output_dict = {} 
for zone, zip, longitude in datarows: 
    count = len(zipcount[zone]) 
    # adjust output dictionary based on the count (1 or more) 
+0

不是爲我工作的;( – sandeep 2013-03-13 15:14:34

+1

@sandeep你必須比這更具體到底是什麼不工作怎麼辦?是錯誤的? – rantanplan 2013-03-13 15:15:25

+1

@sandeep:我不得不猜測你的數據結構是什麼樣子的,因爲你沒有包含代碼。'不爲我工作'我告訴我什麼都沒有,恐怕是 – 2013-03-13 15:17:39