Select to view content in your preferred language

Task with Dictionary

2706
12
05-05-2017 01:11 AM
JohnMcoy
Occasional Contributor

Hi, 

Could you explain me, how to change field value with dictionaries? 

for example : 

dict = {"A" : "A-150",

            "B" : "B-200",

            "C" : "C-250"}

And i want change A with A-150, B with B-200

Thanks ! 

0 Kudos
12 Replies
JohnMcoy
Occasional Contributor

It has to be a piece of that script. You see like this part(code) if any row hasn`t a value, in CSV will write Null.

for n,i in enumerate(row):
                    if i==None:
                         row[n]="NULL"

So I think I need only a couple lines of code to reach a goal. 

Now I have this: 

for key, value in dict.items()
                row[1]=value
0 Kudos
DanPatterson_Retired
MVP Emeritus

you still need the def example and you call it

if i is None:

    row = "NULL"

else:

    row = get_val(i)  # get)val is the def and it needs your dictionary

0 Kudos
BlakeTerhune
MVP Regular Contributor

If there's no extra logic involved with getting the value, why not just look it up in the dictionary immediately instead of making a separate function?

dict = {
    "A": "A-150",
    "B": "B-200",
    "C": "C-250"
}

for n, i in enumerate(row):
    if i:
        row[n] = dict[i]
    else:
        row[n] = None‍‍‍‍‍‍‍‍‍‍‍

Keep in mind that you will get a KeyError and the script will stop if i is not in the dictionary. You can use dict.get() and specify a default value if you want it to keep running.

0 Kudos