Adding a separate string to each item in the list - python

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))

Related

Converting nested lists to dictionary with self generated keys

My list of lists looks like this:
my_list = [[sub_list_1],[sub_list_2],...,[sub_list_n]]
Desired output
my_dict[1] = [sub_list_1]
my_dict[2] = [sub_list_2]
my_dict[n] = [sub_list_n]
I want the keys for the dictionary to be generated on their own. How can this be achieved in a pythonic way?
I look at certain questions like
Converting list of lists in dictionary python
Python: List of lists to dictionary
Converting nested lists to dictionary
but they either provide a list of keys or focus on using some information from the lists as keys.
Alternatively, I tried making a list of keys this way:
my_keys = list(range(len(my_list)))
my_dict = dict(zip(my_keys,my_list)
and it works but, this does not:
my_dict = dict(zip(list(range(len(my_list))),my_list))
This gives me a syntax error.
So in summary:
Is there a way to generate a dictionary of lists without explicitly providing keys?, and
Why does the combined code throw a syntax error whereas the two step code works?
I would recommend to use a dict comprehension to achieve what you want like in here, moreover I tried your implementation and haven't faced any issues (more details are more than welcome):
my_list = [["sub_list_1"],["sub_list_2"],["sub_list_3"]]
my_dict = dict(zip(list(range(len(my_list))),my_list))
alternative_dict = {iter:item for iter,item in enumerate(my_list)}
print("yours : " + str(my_dict))
print("mine : " + str(alternative_dict))
output:
yours : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
mine : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
Your syntax error is caused by your variable name try. try is allready a name in python. see try/except
This should do it
my_dict = {my_list.index(i) + 1: i for i in my_list}
Notice that I have added +1 to start at the key 1 instead of 0 to match your expectations
I received no error message when running your code:
>>> my_list = [["hello1"], ["hello2"]]
>>> my_dict = dict(zip(list(range(len(my_list))), my_list))
>>> my_dict
{1: ['hello1'], 2: ['hello2']}
You can create a dict of lists from a list of lists using a dict comprehension:
my_dict = {i: sub_list for i, sub_list in enumerate(my_list)}

Comparing list with dictionary to make new list in python

I have one list and one dictionary. I want to compare the list values with the keys of the dictionary. If I have:
mydict = {'Hello':1,'Hi':2,'Hey':3}
and:
mylist = ['Hey','What\'s up','Hello']
I want the output to be:
output = [3, None, 1]
Thanks!
I tried [mydict[i] for i in mylist] and I get an error instead of None. I then tried using nested for loops (I deleted that bit) but I decided that was to inefficient.
Use a list comprehension:
output = [ mydict.get(key) for key in mylist ]
Note that dict.get returns None if the key is not in the dict.
Use dict.get(), which defaults to None if key does not exist:
[mydict.get(k) for k in mylist]
>>> mydict = {'Hello':1,'Hi':2,'Hey':3}
>>> mylist = ['Hey','What\'s up','Hello']
>>> out = [mydict.get(k) for k in mylist]
>>> out
[3, None, 1]

Joining dictionaries in a for loop

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)

how to iterate values of perticular keys in python dictionary?

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)

How to make dictionary from list

My list:
list = ['name1', 'option1.1 value1.1', 'option1.2 value1.2', 'name2', 'option2.1 value2.1', 'option2.2 value2.2', 'option2.3 value2.3']
And i want create dictionary like this:
dict = {'name1':{'option1.1':'value1.1', 'option1.2':'value1.2'}, 'name2':{'option2.1': 'value2.1', 'option2.2':'value2.2', 'option2.3':'value2.3'}
I don't know how big is my list (numbers of names, options and values). Any idea?
with list and dict comprehension:
id=[b[0] for b in enumerate(lst) if 'name' in b[1]]+[None]
d={lst[id[i]]:dict(map(str.split,lst[id[i]+1:id[i+1]])) for i in range(len(id)-1)}
your original list was here named lst
This is perhaps not as readable as the answer by #sr22222, but perhaps it's faster, and a matter of taste.
Assuming name will always be a single token (also, don't use list and dict as variable names, as they are builtins):
result = {}
for val in my_list:
split_val = val.split()
if len(split_val) == 1:
last_name = split_val[0]
result[last_name] = {}
else:
result[last_name][split_val[0]] = split_val[1]
Note that this will choke if the list is badly formatted and the first value is not a name.

Categories

Resources