Reputation: 25
I have two lists that have a relationship with each other. List1 is descriptors and List2 is rankings of those descriptions
list1 = ["String1", "String2", "String3"]
list2 = ["2", "1", "3"]
What I want to be able to do is create variables that link these up. So if I want to print ranking number 1, I would get what was originally string2
.
What's the best way to approach this?
Upvotes: 0
Views: 591
Reputation: 3555
Use a dictionary, such as
content = {"2":"String1", "1":"String2", "3":"String3"}
print content["1"]
If you would like to generate the dic from list, you could:
content = dict((key, value) for (key, value) in zip(list2, list1))
Thanks to @minitech, a much more beautiful statement would be:
content = dict(zip(list2, list1))
Upvotes: 2
Reputation: 34146
You could try a dictionary. Dicionaries contain key:value pairs:
rankings = {"1":"String2", "2":"String1", "3":"String3"}
then you can access the elements like:
print rankings["1"]
it will print
"String2"
But how to create this dictionary? Use a for
loop (assuming list1
and list2
have the same length)
rankings = {} # Create empy dicionary
for i in range(len(list2)): # Loop 'n' times, where 'n' is the length of the lists
rankings[list2[i]] = list1[i]
Note: Depending in your implementation, you could just use a number, instead of a string
as key in the dictionary:
rankings = {1:"String2", 2:"String1", 3:"String3"}
Upvotes: 0