building a dictionary dynamically

Dave Angel d at
Tue Feb 7 05:43:36 CET 2012

On 02/04/2012 01:13 PM, noydb wrote:
> How do you build a dictionary dynamically?  Doesn't seem to be an
> insert object or anything.  So I need an empty dictionary that I then
> want to populate with values I get from looping through a list and
> grabbing some properties.  So simply, I have (fyi, arcpy = module for
> interacting with gis data)
>>>> inDict = {}
>>>> for inFC in inFClist:
>>>>      print inFC
>>>>      inCount =  int(arcpy.GetCount_management(inFC).getOutput(0))
> where I want to make a dictionary like {inFC: inCount, inFC:
> inCount, ....}
> How do I build this???
> And, is dictionaries the best route go about doing a comparison, such
> that in the end I will have two dictionaries, one for IN and one for
> OUT, as in I'm moving data files and want to verify that the count in
> each file matches between IN and OUT.
> Thanks for any help!
A dictionary is a mapping from key to value.  So each entry consists of 
a key and a value, where the key is unique.  As soon as you add another 
item with the same key, it overwrites the earlier one.  The only other 
important constraint is that the key has to be of an immutable type, 
such as int or string.

So you want to add the current inFC:inCount as an item in the 
dictionary?  Put the following in your loop.
      inDict[inFC] = inCount

You might also want to check if the key is a duplicate, so you could 
warn your user, or something.  Easiest way to do that is
       if inFC in inDict:



More information about the Python-list mailing list