-1

Hello I have a list that looks like:

>>>ids
 '70723295',
 '75198124',
 '140',
 '199200',
 '583561',
 '71496270',
 '69838760',
 '70545907',
 ...]

I also have a dictionary that gives those numbers a 'name'. Now I want to create a new list that contains only the names, in the order like the numbers before.. so replace the numbers in the right order with the right names from the dictionary.

I tried:

with open('/home/anja/Schreibtisch/Master/ABA/alltogether/filelist.txt') as f:
    ids = [line.strip() for line in f.read().split('\n')]

rev_subs = { v:k for v,k in dictionary.items()}
new_list=[rev_subs.get(item,item)  for item in ids]

#dict looks like:
 '16411': 'Itgax',
 '241041': 'Gm4956',
 '22419': 'Wnt5b',
 '20174': 'Ruvbl2',
 '71833': 'Dcaf7',
 ...}

But new_list is still the same as ids.

What am I doing wrong?

Anja
  • 345
  • 5
  • 21

2 Answers2

1

Maybe the dictionary keys are not in the format you think? Maybe the dictionary contains integers, meanwhile the ids are strings. I would investigate on that, it seems a mismatch of types more than an empty (or non-matching) dictionary.

pierpytom
  • 1,202
  • 1
  • 12
  • 25
  • if I do types1 = set(type(k) for k in final_dictionary1.keys())I got: {NoneType, bs4.element.NavigableString} – Anja Apr 29 '20 at 11:56
  • You don't have a string, but rather _bs4.element.NavigableString_, so the matching doesn't work. You need to convert you _bs4.element.NavigableString_ objects to string, looking at the documentation at https://www.crummy.com/software/BeautifulSoup/bs4/doc/, you need to do unicode(your_element) to convert it. – pierpytom Apr 30 '20 at 12:33
  • But then I have no dictionary anymore.. how can I use that then for my new list? Looks like that now: \n66583\n100504140\n20747\n105638\n320237\n382030\n56758' – Anja Apr 30 '20 at 13:28
  • I have no experience with BeautifulSoup (I just know because I searched for your class), I don't really know how to handle that (I'd look for something like [this](https://stackoverflow.com/questions/1207457/convert-a-unicode-string-to-a-string-in-python-containing-extra-symbols)). At the core, when you create your dictionary, your key must be comparable a string. Btw, your IDs looks a lot like integers, are you sure using string is the best approach? Note, if IDs have leading 0s (e.g. 0042), then I'm wrong and you have to use a string. – pierpytom May 01 '20 at 14:14
1

Your dictionary keys are bs4.element.NavigableString objects rather than strings, so you cannot use strings as keys to look up its values.

You can fix this by converting the keys to strings when you build rev_subs:

rev_subs = {str(k): v for k, v in dictionary.items()}
blhsing
  • 91,368
  • 6
  • 71
  • 106