2013-03-13 70 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