Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

loops - Iterating thru a not so ordinary Dictionary in python 3.x

Maybe it is ordinary issue regarding iterating thru a dict. Please find below imovel.txt file, whose content is as follows:

{'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}

As you can see this is not a ordinary dictionary, with a key value pair; but a key with a list as key and another list as value

My code is:

#/usr/bin/python

def load_dict_from_file():
    f = open('../txt/imovel.txt','r')
    data=f.read()
    f.close()
    return eval(data)
thisdict = load_dict_from_file()
for key,value in thisdict.items():
    print(value)

and yields :

['primeiro', 'segundo', 'terceiro'] ['101', '201', '301']

I would like to print a key,value pair like

{'primeiro':'101, 'segundo':'201', 'terceiro':'301'}

Given such txt file above, is it possible?

question from:https://stackoverflow.com/questions/65830980/iterating-thru-a-not-so-ordinary-dictionary-in-python-3-x

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As other folks have noted, that looks like JSON, and it'd probably be easier to parse it read through it as such. But if that's not an option for some reason, you can look through your dictionary this way if all of your lists at each key are the same length:

for i, res in enumerate(dict[list(dict)[0]]):
    ith_values = [elem[i] for elem in dict.values()]
    print(ith_values)

If they're all different lengths, then you'll need to put some logic to check for that and print a blank or do some error handling for looking past the end of the list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...