Question

I am trying to create Python script that read arguments into a dictionary and then prints the value of 'sender-ip'

The script is invoked with

python lookup.py "email=joe@aol.com, sender-ip=10.10.10.10"

And here is the script

from sys import argv

script, input = argv

attributeMap = {}
delimiter = "="
for item in input:

    if delimiter in item:
        tuple = item.split(delimiter)
        print tuple[0]
        print tuple[1]
        attributeMap[tuple[0]]= tuple[1]
        print attributeMap[tuple[0]]

print attributeMap['sender-ip']
Was it helpful?

Solution

input is not a list; it is a string. You'd need to split that string into items first:

items = input.split(', ')
for item in items:

Do note that there is a built-in function called input() as well, try not to use the name and mask the built-in.

Here is some code that produces a dictionary from your input:

import sys

argument = sys.argv[1]
attr_map = dict(item.strip().split('=', 1) for item in argument.split(','))
print attr_map['sender-ip']

OTHER TIPS

With docopt it is easy.

Having docopt installed:

$ pip install docopt

rewrite your solutions like this lookup.py:

"""Usage: lookup.py <e-mail> <sender-ip>

Arguments:
  <e-mail>     e-mail address
  <sender-ip>  IP address

Sample use:

  $ python lookup.py john.doe@example.com 1.2.3.4
"""
from docopt import docopt

if __name__ == "__main__":
    args = docopt(__doc__)
    attributeMap = {"e-mail": args["<e-mail>"], "sender-ip": args["<sender-ip>"]}
    print attributeMap

and call from command line.

First to remember, how to call it (I choose positional arguments, you may use options too)

$ python lookup.py -h
Usage: lookup.py <e-mail> <sender-ip>

Arguments:
  <e-mail>     e-mail address
  <sender-ip>  IP address

Sample use:

  $ python lookup.py john.doe@example.com 1.2.3.4

and finally see, how the dictionary you asked for gets populated:

$ python lookup.py john.doe@example.com 1.2.34
{'e-mail': 'john.doe@example.com', 'sender-ip': '1.2.34'}

Obviously you meant "email=joe@aol.com, sender-ip=10.10.10.10"

Here's a snippet:

def toDict(s):
  result = {}
  for piece in s.split(','):
    # piece is like 'foo=bar' here
    key, value = piece.split('=')
    result[key.strip()] = value.strip() # .strip() removes spaces around
  return result

How it works:

>>> arg_string = "email=joe@aol.com, sender-ip=10.10.10.10"
>>> toDict(arg_string)
{'email': 'joe@aol.com', 'sender-ip': '10.10.10.10'}
>>> _
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top