1

I have a file with 2 columns:

Anzegem             Anzegem
Gijzelbrechtegem    Anzegem
Ingooigem           Anzegem
Aalst               Sint-Truiden
Aalter              Aalter

The first column is a town and the second column is the district of that town.

I made a dictionary of that file like this:

def readTowns(text): 
    input = open(text, 'r')
    file = input.readlines()
    dict = {}
    verzameling = set()
    for line in file:
        tmp = line.split()
        dict[tmp[0]] = tmp[1]
    return dict

If I set a variable 'writeTowns' equal to readTowns(text) and do writeTown['Anzegem'], I want to get a collection of {'Anzegem', 'Gijzelbrechtegem', 'Ingooigem'}.

Does anybody know how to do this?

Alex
  • 21,273
  • 10
  • 61
  • 73
Dries Coppens
  • 1,085
  • 9
  • 20
  • Possible duplicate of http://stackoverflow.com/questions/7657457/finding-key-from-value-in-python-dictionary – Ray Toal Mar 06 '16 at 21:18
  • You can only have one value for a given key, but that value *can* be a collection... – jonrsharpe Mar 06 '16 at 21:18
  • Why would `Aalst` and `Aalter` not be included? When you say "collection", do you mean "[set](https://docs.python.org/3/library/stdtypes.html#set)"? – ChrisGPT was on strike Mar 06 '16 at 21:18
  • You have not understood the concept of dicts yet. `writeTown['Anzegem']`returns the *values* associated to the *key* `'Anzegem'`. You are looking for the *keys* associated with the *value* `'Anzegem'` – rafaelc Mar 06 '16 at 21:20

4 Answers4

1

If you build your dictionary as {town: district}, so the town is the key and the district is the value, you can't do this easily*, because a dictionary is not meant to be used in that way. Dictionaries allow you to easily find the values associated with a given key. So if you want to find all the towns in a district, you are better of building your dictionary as:

{district: [list_of_towns]}

So for example the district Anzegem would appear as {'Anzegem': ['Anzegem', 'Gijzelbrechtegem', 'Ingooigem']}

And of course the value is your collection.

*you could probably do it by iterating through the entire dict and checking where your matches occur, but this isn't very efficient.

bignose
  • 30,281
  • 14
  • 77
  • 110
ubadub
  • 3,571
  • 21
  • 32
1

You could do something like this, although, please have a look at @ubadub's answer, there are better ways to organise your data.

 [town for town, region in dic.items() if region == 'Anzegem']
Alex
  • 21,273
  • 10
  • 61
  • 73
1

I think you can just create another function that can create appropriate data structure for what you need. Because, at the end you will end up writing code which basically manipulates the dictionary returned by readTowns to generate data as per your requirement. Why not keep the code clean and create another function for that. You Just create a name to list dictionary and you are all set.

def writeTowns(text):
    input = open(text, 'r')
    file = input.readlines()
    dict = {}
    for line in file:
        tmp = line.split()
        dict[tmp[1]]  = dict.get(tmp[1]) or [] 
        dict.get(tmp[1]).append(tmp[0])
    return dict


writeTown = writeTowns('file.txt')
print writeTown['Anzegem']

And if you are concerned about reading the same file twice, you can do something like this as well,

def readTowns(text): 
    input = open(text, 'r')
    file = input.readlines()
    dict2town = {}
    town2dict = {}
    for line in file:
        tmp = line.split()
        dict2town[tmp[0]] = tmp[1]
        town2dict[tmp[1]]  = town2dict.get(tmp[1]) or [] 
        town2dict.get(tmp[1]).append(tmp[0])
    return dict2town, town2dict

dict2town, town2dict = readTowns('file.txt')
print town2dict['Anzegem']
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
1

It sounds like you want to make a dictionary where the keys are the districts and the values are a list of towns. A basic way to do this is:

def readTowns(text): 
    with open(text, 'r') as f:
        file = input.readlines()
        my_dict = {}
        for line in file:
            tmp = line.split()
            if tmp[1] in dict:
                my_dict[tmp[1]].append(tmp[0])
            else:
                my_dict[tmp[1]] = [tmp[0]]
    return dict

The if/else blocks can also be achieved using python's defaultdict subclass (docs here) but I've used the if/else statements here for readability.

Also some other points: the variables dict and file are python types so it is bad practice to overwrite these with your own local variable (notice I've changed dict to my_dict in the code above.

bunji
  • 5,063
  • 1
  • 17
  • 36