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?
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))
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"}
Related
Below is the code:
s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))
I would like to understand how this works. Will it perform for loop first or will it split first?
List of dictionary
s1= "Name1=Value1,Name2=Value2,Name3=Value3;Name1=ValueA,Name2=ValueB,Name3=ValueC"
If you have python installed, I recommend using its interactive repl
With the repl you can run the parts of your program step by step:
s.split(";") will give you ['Name1=Value1', 'Name2=Value2', 'Name3=Value3']
['Name1=Value1', 'Name2=Value2', 'Name3=Value3']
item.split("=") for item in s.split(";") will give you a python generator that iterates on the the list from step 1 and split it off like into smaller lists like this:
[['Name1', 'Value1'], ['Name2', 'Value2'], ['Name3', 'Value3']]
Finally dict(...) on the pairs will turn them into key-value pairs in a python dictionary like this:
{'Name1': 'Value1', 'Name2': 'Value2', 'Name3': 'Value3'}
dict is being passed a generator expression, which produces a sequence of lists by first calling s.split(";"), then yielding the result of item.split("=") for each value in the result of the first split. A more verbose version:
s = "..."
d = dict()
name_value_pairs = s.split(";")
for item in name_value_pairs:
name_value = item.split("=")
d.update([name_value])
I use d.update rather than something simpler like d[x] = y because both dict and d.update can accept the same kind of sequence of key/value pairs as arguments.
From here, we can reconstruct the original by eliminating one temporary variable at a time, from
s = "..."
d = dict()
for item in s.split(";"):
name_value = item.split("=")
d.update(name_value)
to
s = "..."
d = dict()
for item in s.split(";"):
d.update([item.split("=")])
to
s = "..."
d = dict(item.split("=") for item in s.split(";"))
If you write it like that, you might understand better what's happening.
s= "Name1=Value1;Name2=Value2;Name3=Value3"
semicolon_sep = s.split(";")
equal_sep = [item.split("=") for item in semicolon_sep]
a = dict(equal_sep)
print(a["Name1"])
First, it splits the text from wherever there is a semicolon. In this way, we create a list with three elements as "semicolon_sep":
>>> print(semicolon_sep)
['Name1=Value1', 'Name2=Value2', 'Name3=Value3']
Then, it makes a loop over this list to separate each item wherever there is "=". In this way, we have 2 columns for each item (Name and Value). By putting this list (equal_sep) in dict() we change the list to a dictionary.
The codes:
Cour_det = [("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")];
Stu_det = [("UGM2018001","Rohit Grewal"),("UGP2018132","Neha Talwar")];
Grades = [("UGM2018001", "MA101", "AB"),("UGP2018132", "PH101", "B"),
("UGM2018001", "PH101", "B")];
Cour_det = sorted(Cour_det, key = lambda x : x[0]);
Stu_det = sorted(Stu_det, key = lambda x : x[0]);
Grades = sorted(Grades, key = lambda x : x[1]);
Grades = sorted(Grades, key =lambda x : x[0]);
B={}
#code by which i tried to add grade to nested list
for i in range(len(Stu_det)):
for j in range(len(Cour_det)):
B[Stu_det[i][0]][Cour_det[j][0]]=(Cour_det[j][1],Grades[][])
#here i am stuck on how to access grade of the course that i am adding
#it should look like this
B={"UGM2018001":{"MA101":("Calculus","AB'),"PH101":("Mechanics","B")}}
#above list for roll no UGM2018001,similarly other roll no.s as keys and
#course code can be keys of nested list for those roll no.s
In this code i want to make a nested dictionary in which the outer keys will be the roll no as what first element of every tuple of List Stu_det is(like UGM2018001) and then the nested keys will be the course code(like MA101) and then the element of each nested key will be a tuple or list which will have two elements, first element will be the course name(like Calculus) and second element i want the grade mentioned (like AB) but accessing the grade is becoming problem ,how to access it or to get its index. I am unable to get Grade of subject after making roll no. and course code key.
Here's a way of doing it using defaultdict module.
# load library
from collections import defaultdict
# convert to dictionary as this will help in mapping course names
Cour_det = dict(Cour_det)
Stu_det = dict(Stu_det)
# create a dictionary for grades
grades_dict = defaultdict(list)
for x in Grades:
grades_dict[x[0]].append(x[1:])
# create a new dict to save output
new_dict = defaultdict(dict)
# loop through previous dictionary and replace course codes with names
for k,v in grades_dict.items():
for val in v:
temp = list(val)
temp[0] = Cour_det[temp[0]]
new_dict[k].update({val[0]: tuple(temp)})
# print output
print(new_dict)
defaultdict(dict,
{'UGM2018001': {'MA101': ('Calculus', 'AB'),
'PH101': ('Mechanics', 'B')},
'UGP2018132': {'PH101': ('Mechanics', 'B')}})
All I have is one list like below:
list = [ [{u'name': u'Peter'} , {u'name': u'Kevin'} , {u'name': u'Earl'}] ]
I need to get Peter Kevin Earl separately and use that as a parameter to query. How do I write my for loop?
I think there is one list in my list and inside the list has three dictionaries. I need to fetch per dictionary's value.
This would do the trick:
inner_values = [dictionary.values()[0] for dictionary in list[0]]
This solution will get you value out of the inner maps no matter what the key is.
lst = [[{u'name': u'Peter'}, {u'name': u'Kevin'}, {u'name': u'Earl'}]] # Note that this is a list containing another list, containing dictionaries.
names = [x["name"] for x in lst[0]]
I had to change your original list, because "Earl" was listed as a number. :)
first_list = [[{u'name': u'Peter'},{u'name': u'Kevin'},{u'name': u'Earl'}]]
names = []
# You loop over the whole list
for element in first_list:
# For each element, you loop over the elements inside it
for object in element:
# Now, object is each one of the dictionaries
names.append(object["name"])
The code above should works, and here you have a more pythonic answer
# By list comprehension
names = [ x["name"] for x in temp_list for temp_list in first_list ]
# If you don't know the how the key is named
names = [ x.values()[0] for x in temp_list for temp_list in first_list ]
It doesn't matter how many lists you have inside the first list because you are looping over it. And if there is only a list, the loop will iterate once.
Say I have a dictionary of lists,
C = {}
li = []
li.append(x)
C[ind] = li
And I want to check if another list is a member of this dictionary.
for s in C.values():
s.append(w)
Python checks it for any occurrences of the values in s and the dictionary values. But I want to check if any of the lists in the dictionary is identical to the given list.
How can I do it?
Use any for a list of lists:
d = {1 : [1,2,3], 2: [2,1]}
lsts = [[1,2],[2,1]]
print(any(x in d.values() for x in lsts))
True
d = {1:[1,2,3],2:[1,2]}
lsts = [[3,2,1],[2,1]]
print(any(x in d.values() for x in lsts))
False
Or in for a single list:
lst = [1,2]
lst in d.itervalues()
Python will compare each element of both lists so they will have to have the same order to be equal, even if they have the same elements inside the order must also be the same so a simple comparison will do what you want.
in does the trick perfectly, because it does a comparison with each element behind the scenes, so it works even for mutable elements:
lst in d.values()
I need to convert a list into a dictionary in Python.
The list is:
list = [['a','aa','aaa'],['b','bb','bbb']]
And I want to convert it to a dictionary such that:
dictionary = {'aaa': ['a','aa'], 'bbb': ['b','bb']]
I'm looking for a variant of:
d = {i:j for i,j in list}
Thanks in advance!.
With list slicing, where [-1] grabs the last element of the list, and [:-1] grabs all elements up to the last:
Try refraining from using list as a variable name, since it is a built-in type:
d = {x[-1]: x[:-1] for x in lst}