[Tutor] updating a dictionary

Emile van Sebille emile at fenx.com
Thu Feb 19 23:50:02 CET 2015


On 2/19/2015 1:19 PM, Chris Stinemetz wrote:
> Hello List,
>
> I have a dictionary that I would like to update/add rows to it as I read a
> file line by line.
>
> The dictionary format looks like:
>
> format = {'Cell': '','7':'','8':'','9':'','2':''}
>
> For each line read in I would simply like to check to see if a Cell
> key;value exists and if it does update the correct key==band(7,8,9,2)
> within the dictionary.
>
> If the Cell doesn't exist do the same thing as above only make sure to
> update the Cell key:value with it's value form the file so it can check to
> see if it exists later. There are duplicate Cell:values in the file so when
> there is a duplicate it will need to look at band to see what key:value to
> update.
>
> Below is what I have attempted thus far. I can provide sample data if
> needed.
>
> Thank you in advance.

I've added comments interspersed below as I try to grok what you've got 
here...

>
> import datetime

don't need this as you replace the value below...

> import string
> import pprint
> from datetime import datetime

''' here.

>
> # Open a files for reading
> inFileOne = open('PRB_utilization.txt', "r")
>
> iDas = "DB"
> oDas = "D"
>
> suffix = (iDas,oDas)
>
> dict = {'Cell': '','7':'','8':'','9':'','2':''}

it's not good form to shadow python types

> for line in inFileOne.readlines():
>      index = line.rstrip("\n").split("\t")

you now have a list of string values...

>
>      cell = index[1]
>
>      if cell.endswith(suffix, 14, 16) is False:

... so they'll never end with numeric values.  Further, "".endswith() 
accepts only one argument so you ought to get an error on this line.

>          eNb = cell[0:8]
>          sector = cell[10:11]
>          band = cell[9:10]
>          dl_prb_utl = index[60]
>          site = eNb + "_" + sector
>
>          if site in dict:

this tests if site is a valid key in dict -- but the only key value 
you've assigned to if 'Cell' so this will always be False...


>              dict['Cell'] = site
>              dict[band] = dl_prb_utl
>          else:

... and the following will always execute.

>              dict['Cell'] = site
>              dict[band] = dl_prb_utl
>
> inFileOne.close();

Perhaps if you provide a sample of what the contents of inFileOne look 
like and what you want dict to look like after each iteration we'd get a 
better idea of what you're trying to accomplish.  As it is, it'd likely 
take someone who recognizes the problem domain to shed light on this.

Emile




More information about the Tutor mailing list