Skip to content

Instantly share code, notes, and snippets.

@tomjuggler
Created January 7, 2022 06:59
Show Gist options
  • Save tomjuggler/6c04d278d5b709d4010888241fc05af5 to your computer and use it in GitHub Desktop.
Save tomjuggler/6c04d278d5b709d4010888241fc05af5 to your computer and use it in GitHub Desktop.
function to unpack an inverted index with Python 3
import collections
def unpack_inverted_index(input):
all_dict = {}
for ind in input:
for i in range(len(input[ind])):
key = input[ind][i]
all_dict[key] = ind
sorted_dict = collections.OrderedDict(sorted(all_dict.items()))
full_string = ""
for item in sorted_dict.values():
full_string += item + " "
return full_string
#example:
test_input = {'Is': [0], 'this': [1, 14], 'the': [3, 16], 'easiest': [4, 17], 'way': [5, 30], 'to': [6, 31], 'unpack': [7], 'an': [8, 26], 'inverted': [9], 'index?': [10], 'I': [11], 'think': [12], 'that': [13], 'is': [15, 25], 'way,': [18], 'please': [19], 'let': [20], 'me': [21], 'know': [22], 'if': [23], 'there': [24], 'easier': [27], 'or': [28], 'better': [29], 'do': [32], 'this!': [34]}
output = unpack_inverted_index(test_input)
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment