Sunday, October 22, 2017

python list and dictionary

#tutorial blog after tihar oct 22/kartik 5

To convert string to a list use split() method
"this is string".split()
>>> "this-is-string".split("-")
['this', 'is', 'string']


join the strings in a list
>>> "".join(["sdf","asdf"])
'sdfasdf'


>>> mylist
['urgen', 'sherpa', 'is', 'persons', 'name', 'w', 'a', 't']
>>> mylist[-3:]=["".join(mylist[-3:])]
>>> mylist
['urgen', 'sherpa', 'is', 'persons', 'name', 'wat']



mydict={"fname":"john","lname":"doe"}
To change keyvalue for key "lname" to "Foe"
and add extra key value - "age"=21

mydict.update({"lname":"Foe","age":21})

result: >>> {'fname': 'john', 'age': 21, 'lname': 'Foe'}

Packing and Unpacking the dictionaries

def main():

    def packer(**kwargs):
        print(kwargs)
     
    def unpacker(fname=None, lname=None):
        if fname and lname:
            print("{} {}".format(fname,lname))
        else:
            print("missing fname or lname")
         
         
    packer(name="urgen",age=22)
    unpacker(**{"fname":"kenneth","lname":"love"})
 
if __name__ ==  "__main__":
    main()
   

def main():

    var={"fname":"urgne","lname":"sherpa","address":"ktm"}
    print("#keys using method 1")
    for k in var:
        #returns the keys
        print(k)
    #keys
    print("#keys using method 2")  

    for k in var.keys():
        #return keys
        print(k)
    #values
    print("#values")
    for k in var.values():
        #returns the key-value individual tuple item
        print(k)
    print("#key and values")
    for i in var.items():
        print(i)
   
if __name__ ==  "__main__":
    main()

No comments:

Post a Comment