I have something like this,
newlist = []
list =['a','b','c','d','e']
dict = {'a':['a','a1','a2','a3'],'b':['b','b1','b2','b3'],.....'e':['e','e1','e2','e3']
}
I have tried like this,
for listval in list:
newlist.append(dict[listval]].values())
But am not getting expected result,my expectation is,
newlist = [['a','a1','a2','a3'],['b','b1','b2','b3'],....,['e','e1','e2','e3']]
new_list = [the_dict[k] for k in the_list]
or if some keys might be missing:
new_list = [the_dict[k] for k in the_list if k in the_dict]
Try this - :
newlist = [dict.get(i) for i in list if dict.has_key(i)]
It will handle key exists and other errors.
Above will work for you.. :)
You can use map if you know for sure that all the keys will be in the list.
list1 =['a','b','c','d','e']
dict1 = {'a':['a','a1','a2','a3'],'b':['b','b1','b2','b3'],'c':['c','c1','c2','c3'],'d':['d','d1','d2','d3'],'e':['e','e1','e2','e3']}
newlist = map(dict1.get, list1)
Related
I have a python list as follows:
new_list = ['emp_salary', 'manager_sal']
I want to change it to below:
['emp_salary' : 'float', 'manager_sal':'float']
I tried something like this:
>>> users_cols = [l+ ": float" for l in new_list]
>>> users_cols
['emp_salary: float', 'manager_sal: float']
But it is not exactly what i want. The actual list is very big and this is a small example
For the sake of completedness:
new_list = ['emp_salary', 'manager_sal']
new_dict = dict.fromkeys(new_list, "float")
Beware that this will work only if you want to have the same value for each of the keys. Do not use this to declare your mutable values (like sets, lists, dictionaries...), tho unless you want them to all point to the same instance.
You can do this to properly define and initialize a dictionary:
new_list = ['emp_salary', 'manager_sal']
users_cols = {}
for key in new_list:
users_cols[key] = 'float'
new_list = ['emp_salary', 'manager_sal']
new_dict = {key: 'float' for key in new_list}
In list there is no such thing you need dictionary for this, which stores key-value pair:
users_col = { key: "float" for key in new_list }
You can try this:
new_list = ['emp_salary', 'manager_sal']
final_dict = dict(map(lambda x: (x, "float"), new_list))
I have a simple for loop
for m in my_list:
x = my_function(m)
my_dictionary = {m:x}
my_function() gives me a string. And if I use print my_dictionary at the end i get
{m1: string1}
{m2: string2}
I want to be able to have one dictionary at the end.
I have tried several methods that I found in other threads.
dic = dict(my_dictionary, **my_dictionary)
dic = my_dictionary.copy()
dic.update(my_dictionary)
But overtime I just get the last dictionary instead of all dictionaries.
I wish I could just add them with +, but you can't do that in python
You can use a dict comprehension to create your main dict:
dic = {m : my_function(m) for m in my_list}
Why are you creating separate dictionaries in the first place? Just set the key in an existing dict on each iteration.
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary[m] = x
Maybe I'm missing something, but isn't your problem just that you want a simple, non-nested dictionary, and you keep overwriting it within the loop? In that case, this small change should suffice:
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary[m] = x
You can update the dictionary as opposed to overwrite it each time.
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary.update({m:x})
print my_dictionary
There is no need to recreate a new dictionnary at each loop iteration.
You can either create the dictionnary before and add items to it as you iterate:
my_dict = {}
for m in my_list:
my_dict[m] = my_function(m)
or you can use a dict comprehension:
my_dict = {m:my_function(m) for m in my_list}
or, in python 2:
my_dict = dict((m,my_function(m)) for m in my_list)
list1=[['a1',1,2,3],['b1',4,5,6],['a2',1,2,3],['b2',4,5,6]...['a10',1,2,3],['b10',4,5,6]]
how can I get a new list2=[['a1',1,2,3],['a2',1,2,3]...['a10',1,2,3]] by keyword 'a' in python?
Use a list comprehension:
list2 = [item for item in list1 if item[0].startswith('a')]
Could use filter:
list2 = filter(lambda item: item[0].startswith("a") , list1)
Just an alternative you may wish to consider if you're going to be filtering that list a lot:
from collections import defaultdict
keyword = defaultdict(list)
for item in list1:
keyword[item[0][0]].append(item)
This then gives you a dict where you can access the items via keyword['a'] or keyword['b'] for instance...
Is there a Pythonic way to change the type of every object in a list?
For example, I have a list of objects Queries.
Is there a fancy way to change that list to a list of strings?
e.g.
lst = [<Queries: abc>, <Queries: def>]
would be changed to
lst = ['abc', 'def']
When str() is used on a Queries object, the strings I get are the ones in the second code sample above, which is what I would like.
Or do I just have to loop through the list?
Many thanks for any advice.
newlst = [str(x) for x in lst]
You could use a list comprehension.
Try this:
new_list = map(str, lst)
Try this (Python 3):
new_list = list(map(str, lst))
or
new_list = [str(q) for q in lst]
Let's say I have:
dic = {"z":"zv", "a":"av"}
## Why doesn't the following return a sorted list of keys?
keys = dic.keys().sort()
I know I could do the following and have the proper result:
dic = {"z":"zv", "a":"av"}
keys = dic.keys()
skeys = keys.sort() ### 'skeys' will be None
Why doesn't the first example work?
.sort doesn't return the list. You could do:
keys = sorted(dic.keys())
sort() modifies the contents of the existing list. It doesn't return a list. See the manual.