from collections import OrderedDict
dict = {}
fp = open('test.txt')
for line in fp.readlines():
    line = line.split(' ')
dict[line[0]] = line[1].replace('\n', '')
fp.close()
dict = OrderedDict(sorted(list(dict.items()), key=lambda t: t[0]))
for key in dict:
    if dict[key] in dict:
        print(key, dict[key], dict[dict[key]])
else:
    print(key, dict[key])
Recursive key value in a file