Which is the best way to make a dictionary of lists?
For instance, if I have lists list1, list2 and want to make a dictionary my_dict like that:
my_dict = ['list1': list1, 'list2': list2]
I've found this example but the best answer is written in 2009. Maybe there are some new more laconic ways to do this?
You need to use curly rather than square brackets, but otherwise this is probably as good as it gets:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3, 4]
my_dict = {'list1': list1, 'list2': list2}
For a dictionary of lists, consider a defaultdict.
A normal dictionary works fine, but it raises an error if a key is not found.
list1 = list("abcd")
list2 = [1, 2, 3, 4]
d = {"list1": list1, "list2": list2}
d["list3"]
# KeyError: 'list3'
This may be disruptive in some applications and may require additional exception handling.
The defaultdict behaves like a normal dict while adding some protection against errors.
import collections as ct
dd = ct.defaultdict(list)
dd.update(d)
dd
# defaultdict(list, {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]})
Adding a missing key will call the default factory function, i.e. list. Here instead of a error, we get an empty container:
dd["list3"]
# []
This entry was added with an empty list.
dd
# defaultdict(list,
# {'list1': ['a', 'b', 'c', 'd'],
# 'list2': [1, 2, 3, 4],
# 'list3': []})
Convert a defaultdict to a regular dict by setting the default factory to None
dd.default_factory = None
dd
# defaultdict(None, {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]})
or by using the dict() builtin:
dict(dd)
# {'list1': ['a', 'b', 'c', 'd'], 'list2': [1, 2, 3, 4]}
If you want to turn the variable name into a key, here is a similar question.
If you just want a dictionary of lists with a sequential key.
def turn_to_dict(*args):
return {i: v for i, v in enumerate(args)}
lst1 = [1, 2, 3, 4]
lst2 = [3, 4, 6, 7]
lst3 = [5, 8, 9]
v = turn_to_dict(lst1, lst2, lst3)
>>> print(v)
{0: [1, 2, 3, 4], 1: [3, 4, 6, 7], 2: [5, 8, 9]}
Try this method, very succinct. Curly braces, not square brackets.
I think that's the shortest way around it.
list1 = [5, 500, 543]
list2 = [4, 4, 4]
my_dict = {'list1':list1, 'list2': list2}
This should work:
my_dict = dict([('list1', list1), ('list2', list2)])
Or, alternatively:
my_dict = {'list1': list1, 'list2': list2}
The result will be the same.
Use the curly brace syntax to define the dictionary, and give each entry in your dictionary a key that corresponds to each value:
list_a = [1,2,3,4,5]
list_b = [6,7,8,9,10]
my_dict = {'list1':list_a, 'list2':list_b}
More in the python docs
Related
Hi can someone help me with the below requirement ?
Please note the list length can be any number , for example i have just put 4.
I need the output as list of dictionaries with 1 value as key and rest of the values clubbed as list of all possible combination.
Thanks in advance.
Input:
List1 = [1,2,3,4]
Output:
List2 = [ {1:[2,3,4]},{2:[1,3,4]},{3:[1,2,4]} ,{4:[1,2,3]}
Try:
List1 = [1, 2, 3, 4]
out = [
{v: [v for idx2, v in enumerate(List1) if idx != idx2]}
for idx, v in enumerate(List1)
]
print(out)
Prints:
[{1: [2, 3, 4]}, {2: [1, 3, 4]}, {3: [1, 2, 4]}, {4: [1, 2, 3]}]
You can do this with a list comprehension. This approach will only remove the index based.
In [1]: [{i: List1[:idx]+List1[idx+1:]}for idx, i in enumerate(List1)]
Out[1]: [{1: [2, 3, 4]}, {2: [1, 3, 4]}, {3: [1, 2, 4]}, {4: [1, 2, 3]}]
if you want to remove all occurrences of the list, you can use this,
[{i: list(filter((i).__ne__, List1[:]))}for idx, i in List1]
Execution with string list,
In [2]: [{i: list(filter((i).__ne__, List1[:]))}for idx, i in enumerate(List1)]
Out[2]:
[{'a': ['b', 'c', 'd']},
{'b': ['a', 'c', 'd']},
{'c': ['a', 'b', 'd']},
{'d': ['a', 'b', 'c']}]
I need to find any intersection in lists and group them in a new list.
I have a dictionary for example:
my_dict = {A:[1, 5], B:[1, 3], C:[0, 5], D:[4, 7], E:[9, 8]}
new_list = [A, B, C]
or the dict
new_dict = [A:[1, 5], B:[1, 3], C:[0, 5]]
explanation of this A B and C have intersected value in 1 and 5.
Here is how you can list all possible intersections:
my_dict = {'A':[1, 5], 'B':[1, 3], 'C':[0, 5], 'D':[4, 7]}
new_list = []
for k in my_dict:
c = [k]
for l in my_dict:
if k!=l:
if any(a==b for a in my_dict[k] for b in my_dict[l]):
c.append(l)
if len(c) > 1:
new_list.append(c)
print(new_list)
Output:
[['A', 'B', 'C'], ['B', 'A'], ['C', 'A']]
This question already has answers here:
How to group a list of tuples/objects by similar index/attribute in python?
(3 answers)
Closed 3 years ago.
I have a heterogeneous list and I want to group its elements by type.
Let's say, I have:
l = [[], 1, 2, 'a', 3, 'b', [5, 6]]
I want:
l = [[[], [5, 6]], [1, 2, 3], ['a', 'b']]
Where the order doesn't really matter.
What's a python-ic way to do that?
I don't want loops inside of loops inside of loops.
Thanks!
Use collections.defaultdict:
from collections import defaultdict
l = [[], 1, 2, 'a', 3, 'b', [5, 6]]
accumulation = defaultdict(list)
for e in l:
accumulation[type(e)].append(e)
result = list(accumulation.values())
print(result)
Output
[[[], [5, 6]], [1, 2, 3], ['a', 'b']]
As an alternative you could use setdefault:
accumulation = {}
for e in l:
accumulation.setdefault(type(e), []).append(e)
You can do the following, using the inbuilt type which gives you the option of either a list or a dictionary as your return values:
l = [[], 1, 2, 'a', 3, 'b', [5, 6]]
rv = dict()
for thing in l:
if type(thing) in rv:
rv[type(thing)].append(thing)
else:
rv[type(thing)] = [thing]
print([x for x in rv.values()])
Output:
[[[], [5, 6]], [1, 2, 3], ['a', 'b']]
or:
>>> rv
{list: [[], [5, 6]], int: [1, 2, 3], str: ['a', 'b']}
I have written the code which works perfectly but I am trying to use only one for loop but it didn't work out
Here is the python code
lst_one=[1,2,3,4,5,6,7,8]
lst_two=['a','b','c','a','b','c','a','a']
result={}
for createname in range(len(lst_one)):
result[lst_two[createname]]=[]
for value in range(len(lst_one)):
result[lst_two[value]].append(lst_one[value])
print(result)
above code result {'a': [1, 4, 7, 8], 'b': [2, 5], 'c': [3, 6]}
it is working fine using two loop
is it possible to use one loop instead of two-loop
I am using range loop, not lambda, zip and .....
Use zip + setdefault:
lst_one = [1, 2, 3, 4, 5, 6, 7, 8]
lst_two = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'a']
result = {}
for o, t in zip(lst_one, lst_two):
result.setdefault(t, []).append(o)
print(result)
Output
{'a': [1, 4, 7, 8], 'b': [2, 5], 'c': [3, 6]}
you can use defaultdict which create a dictionary where type of value you define like list or int or dict and it will handle if the key is there or not . if present then do operation on value and if not then make a key and value air
lst_one=[1,2,3,4,5,6,7,8]
lst_two=['a','b','c','a','b','c','a','a']
from collections import defaultdict
result = defaultdict(list)
for a,b in zip(lst_one, lst_two):
result[b].append(a)
print(dict(result))
output
{'a': [1, 4, 7, 8], 'b': [2, 5], 'c': [3, 6]}
if you not wana use default dict then, you can use below code which doing the same way like default dict
lst_one=[1,2,3,4,5,6,7,8]
lst_two=['a','b','c','a','b','c','a','a']
result ={}
for a, b in zip(lst_one, lst_two):
if b not in result.keys():
result.update({b:[a]})
else:
result[b].append(a)
print(result)
output
{'a': [1, 4, 7, 8], 'b': [2, 5], 'c': [3, 6]}
I'd recommend using groupby from the itertools package if you want to condense this:
from itertools import groupby
{a[0]:[e[1] for e in b] for a,b in groupby(sorted(zip(lst_two, lst_one)), lambda x:x[0])}
Say I have a list of keys belonging in a dictionary:
dict = {"a":[1,2], "b":[3,4], "c":[5,6]}
keys = ["a","b","c"]
What's the most efficient way to replace all the keys in the list with the values in the dictionary?
ie,
keys = ["a","b","c"]
becomes
keys = [[1,2],[3,4],[5,6]]
map makes it easy:
map(d.get, keys)
(Or, in Python 3.x, list(map(d.get, keys)))
Use a list comprehension like so:
>>> # Please don't name a dictionary dict -- it overrides the built-in
>>> dct = {"a":[1,2], "b":[3,4], "c":[5,6]}
>>> keys = ["a","b","c"]
>>> id(keys)
28590032
>>> keys[:] = [dct[k] for k in keys]
>>> keys
[[1, 2], [3, 4], [5, 6]]
>>> id(keys)
28590032
>>>
[:] is only needed if you want the list object to remain the same. Otherwise, you can remove it:
>>> dct = {"a":[1,2], "b":[3,4], "c":[5,6]}
>>> keys = ["a","b","c"]
>>> id(keys)
28561280
>>> keys = [dct[k] for k in keys]
>>> keys
[[1, 2], [3, 4], [5, 6]]
>>> id(keys)
28590032
>>>
If you want a list of ALL the values from a dict, use
>>> d={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> d.values()
['a', 'b', 'c', 'd']
which returns a list of all contained values.
If you want a subset of the keys, you could use:
>>> d={1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> l=[1, 3]
>>> [d[x] for x in l]
['a', 'c']
Please let me know which you were going for...