Nested Dictionaries in an empty dictionary - python

list1 = [[1,2,3],[4,5,6]]
list2 = ['a','b','c']
list3 = ['A','B']
main_list = [{k: dict(zip(list2, sub))} for k,sub in zip(list3, list1)]
print(main_list)
I am trying to work on this code, my goal is to write a dictionary within a nested dictionary. So, basically I'm trying to add the content in the main_list inside an empty dictionary. I'm hoping to get this ouput shown below:
{{'A':{'a':1, 'b':2, 'c':3}, {'B':{'a':4, 'b':5, 'c',6}}}
Please help:(

I think I found a solution:
main_dict = {k: v for i, k in enumerate(list3) for v in [{c: n for c, n in zip(list2, list1[i])}]}
I would not call it 'main_list', given it's a dict.

Related

How to extend a dictionnary in a such way?

I've got this project about stats and I just wondered how to create a list from a dictionnary like this:
{1:3, 2:4} => [1,1,1,2,2,2,2]
Thanks you !
This simple snippet should do it
l = []
for k, v in d.items():
l.extend([k] * v)
You can use list comprehension as:
x = {1:3, 2:4}
res = [k for k, v in x.items() for i in range(v)]
print(res)
Output:
[1, 1, 1, 2, 2, 2, 2]
we can easily do this by getting the keys of the dictionary. so basically 1 and 2 is our keys and its values are the times that it required to be added to list so we will use for loop to achieve the same.
myDict = { 1:3, 2:4 }
myList = list()
for key in myDict.keys():
for i in range(myDict[key]):
myList.append(key)
print(myList)
In above code the first loop will get the keys and the second will iterate to the limit and append the key into the list

How to convert each items of list into a dictionary?

Here I have a list like this.
ls = ['Small:u', 'Small:o']
What I want is to create a dictionary of each list items like this.
dict1 = {'Small':'u'}
dict2 = {'Small':'o'}
How can I do it ? Is it possible?
>>> x = [dict([pair.split(":", 1)]) for pair in ['Small:u', 'Small:o']]
>>> x
[{'Small': 'u'}, {'Small': 'o'}]
Yes, it is possible, but one thing I'm not sure whether is possible (or a good idea at all) is to programmatically assign variable names to new dictionaries, so instead the easier way is to create a dictionary of dictionaries:
dic_of_dics = {}
for index, item in enumerate(ls):
i, j = item.split(':')
dic_of_dics[f'dict{index}'] = {i : j}
This is another way:
ls = ['Small:u', 'Small:o']
dict_list = []
for i in ls:
k, v = i.split(':')
dict_list.append({k: v})
print(dict_list)
print(dict_list[1].values())
Perhaps with minimal line:
ls = ['Small:u', 'Small:o']
dict_list = map(lambda x:dict([x.split(':')]), ls)
# for python3: print(list(dict_list))
# for Python2: print(dict_list)
Explanation: I am using map function to convert the list of string to list of lists. Then I am passing it through dict(to convert them to dictionary).

Create dictionary from dict and list

I have a dictionary :
dicocategory = {}
dicocategory["a"] = ["crapow", "Killian", "pauk", "victor"]
dicocategory["b"] = ["graton", "fred"]
dicocategory["c"] = ["babar", "poca", "german", "Georges", "nowak"]
dicocategory["d"] = ["crado", "cradi", "hibou", "distopia", "fiboul"]
dicocategory["e"] = ["makenkosapo"]
and a list :
my_list = ['makenkosapo', 'Killian', 'Georges', 'poca', 'nowak']
I want to create a new dictionary with my dicocategory's keys as new keys and items of my list as values.
To get the keys of my new dict (removing duplicate content and adapted to my list) I made :
def tablemain(my_list ):
tableheaders = list()
for value in my_list:
tableheaders.append([k for k, v in dicocategory.items() if value in v])
convertlist = [j for i in tableheaders for j in i]
headerstablefinal = list(set(convertlist))
return headerstablefinal
giving me:
['e', 'a', 'c']
My problem is: I don't know how to put the items of my list in the corresponding keys.
EDIT :
Bellow an output of what I want
{"a" : ['Killian'], 'c' : ['Georges', 'poca', 'nowak'], 'e' : ['makenkosapo']}
The list my_list can change, so I want something that can create a new dictionary doesn't matter the list.
If my new list is :
my_list = ['crapow', 'german', 'pauk']
My output will be :
{'a':['crapow', 'pauk'], 'c':['german']}
Do you have any idea?
Thank you
You can use a couple of dictionary comprehensions. Calculate the intersection in the first, and in the second remove instances where the intersection is empty:
my_set = set(my_list)
# calculate intersection
res = {k: set(v) & my_set for k, v in dicocategory.items()}
# remove zero intersection values
res = {k: v for k, v in res.items() if v}
print(res)
{'a': {'Killian'},
'c': {'Georges', 'nowak', 'poca'},
'e': {'makenkosapo'}}
More efficiently, you can use a generator expression to avoid an intermediary dictionary:
# generate intersection
gen = ((k, set(v) & my_set) for k, v in dicocategory.items())
# remove zero intersection values
res = {k: v for k, v in gen if v}
You can get a dictionary containing only keys with values that match your list like this:
{k:v for k,v in dicocategory.items() if set(v).intersection(set(my_list))}
You won't be able to put that directly into a DataFrame though as the lists differ in length.

Create new empty lists from items within a Python list?

my_list = ['c1','c2','c3']
Is there anyway to create a certain amount of new lists based on items inside of a list?
Result would be:
c1 = []
c2 = []
c3 = []
You can do that using globals():
>>> my_list = ['c1','c2','c3']
>>> for x in my_list:
... globals()[x] = []
...
>>> c1
[]
>>> c2
[]
>>> c3
[]
But it's better to use a dict here:
>>> dic = {item : [] for item in my_list}
>>> dic
{'c2': [], 'c3': [], 'c1': []}
Instead of creating new global variables using the names from your list, I would suggest using a dictionary:
my_list = ['c1', 'c2', 'c3']
my_dict = {k: [] for k in my_list}
Then to access one of those lists you could use something like my_dict['c1'] or my_dict['c2'].
Another solution would be to add the new lists as attributes to some object or module. For example:
lists = type('Lists', (object,), {k: [] for k in my_list})
After which you could access your lists using lists.c1, lists.c2, etc.
In my opinion both of these methods are cleaner than modifying globals() or locals() and they give you very similar behavior.
Note that if you are on Python 2.6 or below you will need to replace the dictionary comprehensions with dict((k, []) for k in my_list).

Convert list of keys and list of values to a dictionary [duplicate]

This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 7 months ago.
I have these lists:
list1 = ["a","b","c"]
list2 = ["1","2","3"]
I need to add them to a dictionary, where list1 is the key and list2 is the value.
I wrote this code:
d = {}
for i in list1:
for j in list2:
d[i] = j
print d
The output is this:
{'a':'3','b':'3','c':'3'}
What's wrong with this code? How can I write it so the output is
{'a':'1','b':'2','c':'3'}
Thanks!
Zip the lists and use a dict comprehension :
{i: j for i, j in zip(a, b)}
Or, even easier, just use dict() :
dict(zip(a, b))
You should keep it simple, so the last solution is the best, but I kept the dict comprehension example to show how it could be done.
you are almost there, except you need to iterate over the lists simultaneously
In [1]: list1 = ["a","b","c"]
In [2]: list2 = ["1","2","3"]
In [3]: d = {}
In [4]: for i, j in zip(list1, list2):
...: d[i] = j
...:
In [5]: print d
{'a': '1', 'c': '3', 'b': '2'}
You can also use dict comprehension to do the following in a nice one-liner.
d = {i : j for i, j in zip(list1, list2)}
list1 = ["a","b","c"]
list2 = ["1","2","3"]
mydict = {}
for i,j in zip(list1,list2):
mydict[i] = j
print mydict

Categories