convert multiple lists to a dictionary - python

Is there a way in python to turn a set of lists into a dictionary, where the name of the list is the key and the values are the values? Can you do this with dictionary comprehension?
one = ['a', 'b', 'c']
two = ['d','e','f']
would become
dictionary = {"one" : ['a', 'b', 'c'], "two":['d','e','f'] }

>>> one = ['a', 'b', 'c']
>>> two = ['d','e','f']
>>> c = dict({'one':one, 'two':two})
or
>>> dict(zip(["one", "two"], [one, two]))
Why you want to convert one variable to 'one' and two variable to 'two' is incomprehensible.

I don't think you can necessarily access the variable name, but lets say, if you had a list of those lists, you could set the index of each one as the key value. example:
megaList = [[2, 3, 6], [3, 6, 1]]
dic = {}
for i, l in enumerate(megaList):
dic[i] = l
but in that case you might as well just have the list of lists. Just though I'd share since I'm not sure what you're trying to do, and maybe this can steer you in the right direction.
Or do what #enigma did, if you don't mind typing them out by hand.

Related

How to create a list of list after joining 2 lists in python?

I have 2 list and I am trying to join them and expected is a list of lists.
Can you please suggest on the same?
I have tried using + operator and append as well.
list_output_first = []
list_output_second = []
list_a = [1,2,[]]
list_b = ['a',['b', '']]
list_output_first = list_a + list_b
list_output_first = list_a.append(list_b)
OUTPUT
[1, 2, [], ['a', ['b', '']]]
EXPECTED
[[1, 2, []], ['a', ['b', '']]]
You need to built a main list, that contains the 2 others:
list_output_first = [list_a, list_b]
Or built it empty, and add the 2 others:
list_output_first = []
list_output_first.append(list_a)
list_output_first.append(list_b)
Reference in both example solution up there, you pass the list itself, so if you modify list_a or list_b later, you'll the the changes in list_output_first too. If you want to have a copy of the lists inside list_output_first do
list_output_first = [list(list_a), list(list_b)]
# and for the other:
list_output_first.append(list(list_a))
The + operator for lists sums them together making one list with elements of each, you need an extra container where your put the both lists A list and not their values
just do:
list_output_first = [list_a, list_b]
It is possible to do this :
list_output_first = [list_a] + [list_b]
Just add two list by placing them in a list
list_a = [1,2,[]]
list_b = ['a',['b', '']]
print([list_a]+[list_b])
#[[1, 2, []], ['a', ['b', '']]]
There can be many ways, here I am sharing two ways that I find simple.
first way:- You can extend list_b into list_a and print list_a. If you want to store it in another list that You can create another list and store a copy of list in which you extended other list.
list_a = [1, 2, []]
list_b = ['a', ['b', '']]
list_a.extend(list_b)
list_c = list_a.copy()
print(list_c)
second way:- You can add both list and store it in an empty list.
list_a = [1, 2, []]
list_b = ['a', ['b', '']]
list_c = list_a + list_b
print(list_c)
Hope it will help.
If you want list without backref connection with elements it is made from:
from copy import deepcopy
answer = [ item for item in (deepcopy(list_a), deepcopy(list_b)) ]

How to add a list after an existing list but not expand it?

Hi~ It seems like a simple question, but I failed to find it being asked and answered.
I have a dictionary data_dict like {'keyId':['1','2','3']}.
Now I'd like to add some new lists (namely ['a','b','c']) and make it like {'keyId':['1','2','3'],['a','b','c']}, so I do it as
for new_list in lists:
data_dict[keyId].append(new_list)
But it turned out to be like {'keyId':['1','2','3',['a','b','c']]}.
{'keyId':['1','2','3'],['a','b','c']} is not a valid Python data structure.
What you could do is implement keyId as a list of lists:
data_dict = {'keyId':[['1','2','3']]}
Lists are unhashable – you can't use them in dictionaries because they are mutable. You can use a tuple of the lists instead.
data_dict = {'keyId':(['1','2','3'])}
You need a unique key, something hashable, and as a value, a list, and then you can populate it:
lists = [[2,3,4], [5,4,5], "abd"]
data_dict = {}
keyId = "hashable_obj"
data_dict[keyId] = []
for new_list in lists:
data_dict[keyId].append(new_list)
print(data_dict)
output:
{'hashable_obj': [[2, 3, 4], [5, 4, 5], 'abd']}
The important characteristics of Python lists are as follows:
Lists are ordered.
Lists can contain any arbitrary objects.
List elements can be accessed by index.
Lists can be nested to arbitrary depth.
Lists are mutable.
Lists are dynamic.
List item so I would suggest with list based approach. Here is the source link to understand between list and tuple.
my_list = [[1,2,3], ['a', 'b', 'c']]
my_dict = {}
my_dict['KeyId'] = []
for new_list in my_list:
my_dict['KeyId'].append(new_list)
Output
{'KeyId': [[1, 2, 3], ['a', 'b', 'c']]}

Appending Values from one list to another list based on line?

I'm very new to python, and I want to concatenate each line in one list to another line in another list in python. I would like to put integers from a list in front of a each string in the string list. For example:
int = [1, 2, 3]
string = ['a', 'b', 'c']
final product: [1'a', 2'b', 3'c']
how can I go about doing this?
Assuming you want string concatenation behavior, you can use zip in a list comprehension
>>> nums = [1, 2, 3]
>>> letters = ['a', 'b', 'c']
>>> [str(i) + j for i, j in zip(nums, letters)]
['1a', '2b', '3c']
You could solve this issue like this
final_product = []
for i in range(len(string)):
final_product.append(zip(nums[i], string[i] ))

find indexes of all None items in a list in python

I have a list of strings, some of them are None.
i want to get a new list of all the Indexes of None.
list = ['a', 'b', None, 'c' ,None, 'd']
using the function index
n = list.index(None)
will only return the first appearance, n= 2, while i want to see n= [2,4].
thanks you.
Try enumerate:
l=[i for i,v in enumerate(list) if v == None]
Or range:
l=[i for i in range(len(list)) if list[i] == None]
Both cases:
print(l)
Is:
[2,4]
Big Note: it is not good to name variables a existing method name, that overwrites it, (now it's list), so i would prefer it as l (or something)
I recommend the first example because enumerate is easy, efficient.
Here's something different but it doesn't use list comprehension:
>>> l = ['a', 'b', None, 'c' ,None, 'd']
>>> out = []
>>> for _ in range(l.count(None)):
out.append(l.index(None))
l[l.index(None)] = "w"
>>> out
[2, 4]
>>>
Faster way. Very useful in case of long list.
list = ['a', 'b', None, 'c' ,None, 'd']
import numpy as np
print(np.where(np.array(list) == None)[0])
Output :
[2 4]
In case you need list of index :
print(np.where(np.array(list) == None)[0].tolist())
>>> [2, 4]

Remove list element without mutation

Assume you have a list
>>> m = ['a','b','c']
I'd like to make a new list n that has everything except for a given item in m (for example the item 'a'). However, when I use
>>> m.remove('a')
>>> m
m = ['b', 'c']
the original list is mutated (the value 'a' is removed from the original list). Is there a way to get a new list sans-'a' without mutating the original? So I mean that m should still be [ 'a', 'b', 'c' ], and I will get a new list, which has to be [ 'b', 'c' ].
I assume you mean that you want to create a new list without a given element, instead of changing the original list. One way is to use a list comprehension:
m = ['a', 'b', 'c']
n = [x for x in m if x != 'a']
n is now a copy of m, but without the 'a' element.
Another way would of course be to copy the list first
m = ['a', 'b', 'c']
n = m[:]
n.remove('a')
If removing a value by index, it is even simpler
n = m[:index] + m[index+1:]
There is a simple way to do that using built-in function :filter .
Here is ax example:
a = [1, 2, 3, 4]
b = filter(lambda x: x != 3, a)
If the order is unimportant, you can use set (besides, the removal seems to be fast in sets):
list(set(m) - set(['a']))
This will remove duplicate elements from your original list though
We can do it via built-in copy() function for list;
However, should assign a new name for the copy;
m = ['a','b','c']
m_copy=m.copy()
m_copy.remove('a')
print (m)
['a', 'b', 'c']
print(m_copy)
['b', 'c']
You can create a new list without the offending element with a list-comprehension. This will preserve the value of the original list.
l = ['a', 'b', 'c']
[s for s in l if s != 'a']
Another approach to list comprehension is numpy:
>>> import numpy
>>> a = [1, 2, 3, 4]
>>> list(numpy.remove(a, a.index(3)))
[1, 2, 4]
We can do it without using in built remove function and also without creating new list variable
Code:
# List m
m = ['a', 'b', 'c']
# Updated list m, without creating new list variable
m = [x for x in m if x != a]
print(m)
output
>>> ['b', 'c']
The question is useful as I sometimes have a list that I use throughout my given script but I need to at a certain step to apply a logic on a subset of the list elements. In that case I found it useful to use the same list but only exclude the needed element for that individual step, without the need to create a totally new list with a different name. For this you can use either:
list comprehension: say you have l=['a','b','c'] to exclude b, you can have [x for x in l if x!='b']
set [only if order is unimortant]: list(set(l) - set(['b'])), pay attention here that you pass 'b' as list ['b']

Categories