Home > front end >  How to create tuples from a dictionary of words and values with the value first
How to create tuples from a dictionary of words and values with the value first

Time:04-09

I have a dictionary file, here are a few example lines:

acquires,1.09861228867
acquisition,1.09861228867
acquisitions,1.60943791243
acquisitive,0.69314718056
acridine,0.0
acronyms,1.09861228867
acrylics,0.69314718056
actual,1.60943791243

words = [acquires, acrylics, actual, acridine]

I need the output to be:

word_tuples = ((1.09861228867,acquires),(0.69314718056,acrylics), (1.60943791243,actual),
               (0.0,acridine))

I tried doing,

sorted_list[]
word_tuples = [(key,value) for key, value in dict]
            if words in word_tuples:
                sorted_list.append(word_tuples[value])

CodePudding user response:

You can do something like this:

dict = {"acquires":1.09861228867, "acquisition":1.09861228867, "acquisitions":1.60943791243,
"acquisitive":0.69314718056, "acridine":0.0, "acronyms":1.09861228867, "acrylics":0.69314718056," actual":1.60943791243}

words = ["acquires", "acrylics", "actual", "acridine"]

tuple_list = list()
for key, value in dict.items():
    if key in words:
        tuple_list.append((value, key))
        
print(tuple_list)  

CodePudding user response:

You could do it by using a passing a generator expression to the tuple constructor:

from operator import itemgetter

my_dict = {
    'acquires': 1.09861228867,
    'acquisition': 1.09861228867,
    'acquisitions': 1.60943791243,
    'acquisitive': 0.69314718056,
    'acridine': 0.0,
    'acronyms': 1.09861228867,
    'acrylics': 0.69314718056,
    'actual': 1.60943791243,
}

words = {'acquires', 'acrylics', 'actual', 'acridine'}

word_tuples = tuple((value, word) for word, value in
                        sorted(my_dict.items(), key=itemgetter(0)) if word in words)

Note that I made words a set of strings instead of a list because doing so greatly speeds-up the if word in words membership check.

CodePudding user response:

I would consider iterating over the words List and checking the dictionary for the element. The reason for not doing it the other way around is that searching for an element in a list has a complexity of O(n) while checking the dictionary will have a complexity of O(1) and is therefore much faster.

Here is my solution:

my_dict = {"acquires":1.09861228867, "acquisition":1.09861228867, "acquisitions":1.60943791243,"acquisitive":0.69314718056, "acridine":0.0, "acronyms":1.09861228867, "acrylics":0.69314718056,"actual":1.60943791243}

words = ["acquires", "acrylics", "actual", "acridine"]

word_tuples = list()
for word in words:
    if word in my_dict:
        word_tuples.append((word, my_dict[word]))

print(word_tuples)
  • Related