Érico
Érico

Reputation: 29

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?

Upvotes: 0

Views: 34

Answers (2)

Axe319
Axe319

Reputation: 4365

You should use the builtin json module to parse but either way, you'll still have the same structure.

There are a few things you can do. If you know both of the base key names('Andar' and 'Apto') you can do it as a one line dict comprehension by zipping the values together.

# what you'll get from the file
thisdict = {'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
# One line dict comprehension
newdict = {key: value for key, value in zip(thisdict['Andar'], thisdict['Apto'])}
print(newdict)

If you don't know the names of the keys, you could call next on an iterator assuming they're the first 2 lists in your structure.

# what you'll get from the file
thisdict = {'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
# create an iterator of the values since the keys are meaningless here
iterator = iter(thisdict.values())
# the first group of values are the keys
keys = next(iterator, None)
# and the second are the values
values = next(iterator, None)
# zip them together and have dict do the work for you
newdict = dict(zip(keys, values))
print(newdict)

Upvotes: 1

Joshua Noble
Joshua Noble

Reputation: 894

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.

Upvotes: 0

Related Questions