#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0

    Python List searching


    I have a List which looks like
    Lst = {'id' : [01000], 'region' : ['NE'], 'city' : ['Boston'], 'SKU' : ['A100'], 'email' : ['last.first@email.com']} This list continues with tuples with different 'email' ids.

    I have a mail id as input which is input_id = 'last.first@email.com' . I need to loop thru the lst that contains the tuples till a match is found between the input_id and the email. If exact-match is found, get the rest of the fields and store them in different fields for later processing. I coded as
    Code:
    for entry in Lst:
                data = entry
                for value in data.values():
                    id = data['email']
                    for value in id:
                        eid = value
                        emid = eid.lower()
                        if input_id == emid                  
                            regn = lst['region']
                            city = lst['city']
                            sku = lst['sku']
                            for value in regn:
                                region = value
                            for value in city:
                                citi = value
                            for value in sku:
                                skun = value
                                break                                  
                else:
                   continue
    Any others suggestions! Please share. Thanks.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    This might just be a personal idiosyncrasy of mine but it would help if you used clearer terms. If I understand correctly, each element of your list is a dictionary (not, as you stated, a tuple). You get an email id and you want to find which dictionary has that value for the "email" key. If that's correct, then you're mostly going at it right although it looks like there might be a few small errors. By the way, you don't say just what if any problem you're having.

    I would do something like this (assuming I have your situation correct):
    Code:
    emid="abc.xyz@domain.com"
    for rec in Lst:
        if rec["email"]==emid:
            city=rec["city"]
            #etc for all the fields of interest
            break
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0
    1. Thanks very much. You got the situation correct.
    When I compared the email Ids, It was not matching and so I converted them to lowercase. Like my input had a.name@domain.com where as the dictionary had A.name@domain.com. So rec["email"] == emid: failed due to the uppercase A. In your code, can I add
    if rec["email"].lower() == emid:


    2. I tried the code that was suggested but I am getting an error.
    Code:
         for rec in Lst:
    	if rec['email'] == emid:
    		city = rec['city']
    		sku = rec['SKU']
    		break
    Traceback (most recent call last):
    File "<pyshell#13>", line 2, in <module>
    if rec['email'] == emid:
    TypeError: string indices must be integers, not str
    >>>

    Please let me know if the code I typed is correct.

    3. Now this code will be a called function from some other function(calling). After finding and storing these fields(like region,city,sku), will those fields be visible in the calling function? Do I have to use return to get the visibility?

    Your comments will be appreciated.
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    That error is saying that the elements of Lst are NOT dictionaries, but rather strings. You need to chck to make sure Lst is being built the way yoy think it is.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    7
    Rep Power
    0
    Thanks for the reply. It is JSON strings. I take the input from some other system that gives it in JSON format. So unless I use the value clause, I am not able to get the data out. My code might work but if there ia any better way to match and get the data, I thought of trying out.
  10. #6
  11. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    610
    Rep Power
    65
    Code:
    '''json_dictionary1.py
    module json can be used similar to pickle
    objects like a dictionary can be saved to file as a string
    json --> JavaScript Object Notation
    new since Python26
    tested with Python33
    '''
    
    import json
    
    # note that quotes have to be a certain way
    # mydict_str = "{'a': 1, 'b': 2}"
    # would give a ValueError
    
    # this string can be saved  to a file
    mydict_str = '{"a": 1, "b": 2}'
    
    fname = "json_dict.txt"
    with open(fname, "w") as fout:
        fout.write(mydict_str)
    
    # load a string of an object (json object)
    # and recreate the object
    with open(fname) as fin:
        mydict = json.load(fin)
    
    print(mydict)
    print(type(mydict))
    print(mydict['a'])
    
    '''my result >>>
    {'b': 2, 'a': 1}
    <class 'dict'>
    1
    '''
    Last edited by Dietrich; November 17th, 2012 at 09:01 AM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo