python

Printing elements of dictionary line by line


I have a dictionary in a file and i should write a python code to print the keys and values in seperate lines.(without using .keys() and .values().

For eg: dict={"the":"1", "and":"2"} should return as

the:1          
and:2 

Here is my code i tried. I am new to python dictionary. Please help me fix this.

dict2 = {}

f= open("dict.txt", 'r')
    for line in f:
        it = line.split()
        k, v = it[0], it[1:]
        dict2[k] = v
return (dict2)

Solution

  • If you are trying to print the key values out of a dictionary in the same order as they appear in the file using a standard dict that won't work (python dict objects don't maintain order). Assuming you want to print by the value of the dicts values...

    lines = ["the 1", "and 2"]
    d = {}
    
    for l in lines:
        k, v = l.split()
        d[k] = v
    
    for key in sorted(d, key=d.get, reverse=True):
        print ":".join([key, d[key]])
    

    assuming you can use lambda and string concatenation.

    lines = ["the 1", "and 2"]
    d = {}
    
    for l in lines:
        k, v = l.split()
        d[k] = v
    
    for key in sorted(d, key=lambda k: d[k], reverse=True):
        print key + ":" + d[key]
    

    with out lambda

    for value, key in sorted([(d[k], k) for k in d], reverse=True):
        print key + ":" + value
    

    to make a function out of it

    def lines_to_dict(lines):
        return_dict = {}
        for line in lines:
            key, value = line.split()
            return_dict[key] = value
    
        return return_dict
    
    if __name__ == "__main__":
    
        lines = ["the 1", "and 2"]
        print lines_to_dict(lines)