2

I have a dictionary which i fetch from MySql DB, the ID is the key and the value is a string (relative Windows path of files to be exact). I have another list which has windows path as elements. Now, I need to match the list elements with the dictionary values and if exact match is found, i need to retrieve the key for that element, if not present, i'll update in the DB

My current code:

for line in f1:
        line = line.strip()
        try:
            index = next(k for (k,v) in self.db_file_list.iteritems() if line in v)
            file_list_csv.append(index)

The problem here is: Suppose value in my dictionary is "abc def", "a/b/c" then if i search values "abc" or "a/b" it would still match and give me key value which is not what i want.

Please help me out, i am a newbie to Python. Many thanks in advance!

~Saurav

user2474353
  • 25
  • 1
  • 4
  • 1
    I'm unclear what you're trying to do. Are you trying to go from a key->value mapping to value->key mapping? If yes, are you sure that the value->key mapping is unique? – mgilson Jun 11 '13 at 12:12
  • I think you got it backwards. What you call a "key" here is actually a value, and what you call a value is actually a key. so something like `dict( reverse(x) for x in dic.items() )` might help. – Elazar Jun 11 '13 at 12:13
  • If you're looking for the inverse mapping, this is a duplicate of [this question](http://stackoverflow.com/q/483666/748858) – mgilson Jun 11 '13 at 12:14
  • Hi @mgilson : Yes, the value->key mapping is unique. The table in DB is just a file list, id is auto incremented, so its unique. But even if i go for dict reverse, it wont solve the problem of partial match and not exact match, will it? Thank you! – user2474353 Jun 11 '13 at 12:31

1 Answers1

0

If your only problem is that you would be matching substring matches as well, then replacing line in v with line == v would be enough (take care to use == in this case and not is: is does an identity comparison, whereas == simply compares values).

BergmannF
  • 9,727
  • 3
  • 37
  • 37