I have 2 lists
old_name_list = [a-1234, a-1235, a-1236]
new_name_list = [(a-1235, a-5321), (a-1236, a-6321), (a-1234, a-4321), ... ]
I want to search recursively if the elements in old_name_list exist in new_name_list and returns the associated value with it, for eg. the first element in old_name_list returns a-4321, second element returns a-5321, and so on until old_name_list finishes.
I have tried the following and it doesn't work
for old_name, new_name in zip(old_name_list, new_name_list):
if old_name in new_name[0]:
print new_name[1]
Is the method I am doing wrong or I have to make some minor changes to it? Thank you in advance.
Build a dict() based on your second list, and lookup in that.
old_name_list = ["a-1234", "a-1235", "a-1236"]
new_name_list = [("a-1235", "a-5321"), ("a-1236", "a-6321"), ("a-1234", "a-4321") ]
d = dict(new_name_list)
for n in old_name_list:
print d[n]
You do need to put quotes around strings like "a-1234".
Using a dictionary may be the best way to do this.
old_name_list = ['a-1234', 'a-1235', 'a-1236']
new_name_list = [('a-1235', 'a-5321'), ('a-1236', 'a-6321'), ('a-1234, a-4321')]
mapping = dict(new_name_list)
values = [mapping[item] if item in mapping for item in old_name_list]
print values
Use this:
found_items = [item[1] for item in new_name_list if item[0] in old_name_list]
Related
Hey (Sorry bad english) so am going to try and make my question more clear. if i have a function let's say create_username_dict(name_list, username_list). which takes in two list's 1 being the name_list with names of people than the other list being usernames that is made out of the names of people. what i want to do is take does two list than convert them to a dictonary and set them together.
like this:
>>> name_list = ["Ola Nordmann", "Kari Olsen", "Roger Jensen"]
>>> username_list = ["alejon", "carli", "hanri"]
>>> create_username_dict(name_list, username_list)
{
"Albert Jones": "alejon",
"Carlos Lion": "carli",
"Hanna Richardo": "hanri"
}
i have tried look around on how to connect two different list in too one dictonary, but can't seem to find the right solution
If both lists are in matching order, i.e. the i-th element of one list corresponds to the i-th element of the other, then you can use this
D = dict(zip(name_list, username_list))
Use zip to pair the list.
d = {key: value for key,value in zip(name_list, username_list)}
print(d)
Output:
{'Ola Nordmann': 'alejon', 'Kari Olsen': 'carli', 'Roger Jensen': 'hanri'}
Considering both the list are same length and one to one mapping
name_list = ["Ola Nordmann", "Kari Olsen", "Roger Jensen"]
username_list = ["alejon", "carli", "hanri"]
result_stackoverflow = dict()
for index, name in enumerate(name_list):
result_stackoverflow[name] = username_list[index]
print(result_stackoverflow)
>>> {'Ola Nordmann': 'alejon', 'Kari Olsen': 'carli', 'Roger Jensen': 'hanri'}
Answer by #alex does the same but maybe too encapsulated for a beginner. So this is the verbose version.
I'm trying to add every value under "title" from a dictionary to a list but i always get KeyError: 'title'.
list = []
q = input("Search:")
search = SearchVideos(q, mode = 'dict')
dictt = (search.result())
print(dictt)
for i in dictt:
list.append(dictt['title'])
you have a few problems here.
First, you're not accessing the right value. It looks like dictt has only one key: search_result and you should iterate on it's value.
In addition, list.append(value) will not add the value to a list. you need to make a list and then do new_list.append(value).
lastly you didn't use i in your loop.
It should look like this:
new_list = []
for item in dictt['search_result']:
new_list.append(item['title'])
I have this list with dictionary data type:
venueList = [{'VIP Room':10,'Executive Room':30,'Pool Site':50}]
And I have this program:
print([d['VIP Room'] for d in venueList])
where it prints:
[10]
how to remove the [] symbol and is there a much simpler ways to print it.Thanks
Assuming you have only 1 element(dict) in the list
venueList[0]['VIP Room']
#Output:
#10
Right now your list only has one element (it's a singleton list), so it might make sense to print just the lone element. However, consider what you want for when there is more than just one element.
k = [d['VIP Room'] for d in venueList]
First we start with that.
If you want to output them as a list, just print(k). However, if you want the [] gone and using commas for separation, you can do print(", ".join(str(e) for e in k)). If you want to print them with spaces as separation, you can do print(*k), which equates to calling print(k[0], k[1], ..., k[-1]).
for d in venueList:
print(d['VIP Room'])
Considering you have a list with only one element, and that element is a dict, you just need to unwrap the value, take the list away, and print the value assoc to the key you want:
venueList = [{'VIP Room':10,'Executive Room':30,'Pool Site':50}]
print(venueList.pop()['VIP Room'])
You can check it here: https://repl.it/NW0S/1
I'm maintaining message_id and message_writer_id together in a python list like so:
composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...]
Where each element is message_id:message_poster_id.
From the above list, I want to extract the set of all message_writer_ids. I.e. I want to extract a set containing all unique numbers after : so that I end up with:
item_set = ['2', '1', '19']
What's the most efficient way to do that in python?
Currently, I'm thinking I'll do something like:
new_list = []
for item in composite_items:
element = item.split(":")[1]
new_list.append(element)
new_set = set(new_list)
Was wondering if there's a faster way to achieve this.
You may use set comprehension like so:
new_set = {item.partition(":")[2] for item in composite_items}
Set comprehension is fast, and unlike str.split(), str.partition() splits only once and stops looking for more colons. Quite the same as with str.split(maxsplit=1).
composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...]
posters = dict()
for element in composite_items:
poster_id = element.split(":")[1]
posters[poster_id] = posters.get(poster_id, 0) + 1
You can use dictionaries and also count how many messages sent by message_poster_id. posters.get(poster_id,0) + 1 checks that a poster exists or not. If exists it gets its value (number of messages) and increment it by 1.
If doesn't exist its add the poster_id to dictionary and sets it to 0.
I have a list which grows and shrinks in a for loop. The list looks like following :- . With every element inside list of list i want to associate it to a separate dictionary.
list123 = [[1010,0101],[0111,1000]]
In this case I want to create 4 dictionary with the following name
dict1010 = {}
dict0101 = {}
dict0111 = {}
dict1000 = {}
I tried following loop
for list1 in list123:
for element in list1:
dict + str(element) = dict()
This is the error i am getting
SyntaxError: can't assign to literal
while you can dynamically create variables, unless there is an overwhelming need to do that use instead a dictionary of dictionary witch key is the name you want, like this
my_dicts=dict()
for list1 in list123:
for element in list1:
my_dicts["dict" + str(element)] = dict()
and to access one of them do for example my_dicts["dict1010"]
You can uses globals() function to add names to global namespace like this
for list1 in list123:
for element in list1:
globals()["dict"+str(element)] = {}
this will add variables with the names you want as if you created them using dictx={} also numbers that begins with 0 won't convert well using str() so you should make your list a list of strings
First of all, I must say that you shouldn't do this. However, if you really want to, you can use exec.
If you really want to do this, you could use exec:
list123 = [[1010,0101],[0111,1000]]
for list1 in list123:
for element in list1:
var = 'dict' + str(element)
exec(var + ' = dict()')