How to put 2 dictionaries in one dictionary as elements? - python

I am looking to put 2 dictionaries into one dictionary.
note. I am not looking to merge them or join them. I am looking for a method similar append for dictionary.
Note;
I want them to hold their structures. don't want the data to mix up
Example
I Have this,
dic1 = {'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'}
dic2 = {1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}
I want this
dic3 = {{'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'},
{1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}}
Thanks in advance

That's not how dictionaries work. You can have a list or tuple (or possibly a frozenset) that looks mostly like what you want, but dictionaries do not allow this kind of linear concatenation. They are strictly associative containers, meaning that every value must have an associated key.
If you can associate each dictionary with a key, however, then what you want becomes extremely straightforward:
dic3 = {
'dic1': {'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'},
'dic2': {1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}
}
Or, using your variables:
dic3 = {'dic1': dic1, 'dic2': dic2}

Update: check the added example at the bottom.
If you don't want to change dic1 or dic2, you can do this:
dic3 = {**dic1, **dic2}
dic3 will be a dictionary.
Any common key will have the value appearing later (to the right).
For the type of output you expect (set of dictionaries), you need to create a hashable dictionary as follows:
class hashabledict(dict):
def __hash__(self):
return hash(tuple(sorted(self.items())))
dic1 = {'Apple':'Mac', 'Microsoft': 'Surface', 'Google': 'Chromebook', 'Lenovo':'ThinkPad'}
dic2 = {1:'Apple', 2:'Amazon', 3:'Microsoft', 4:'Google', 5:'Facebook'}
dic3 = {hashabledict(dic1), hashabledict(dic2)}
The above hashabledict class definition has been taken from here: Python hashable dicts

Related

How to extract the given keys in one dictionary from another into a new dictionary (Python)

I'm trying to practice sets and dictionaries, and one thing I've been finding is myself stuck on this practice problem over and over.
For example if I have a dictionary like
employees =[
{
"name": "Jamie Mitchell",
"job": "Head Chef",
"city": "Toronto",
},
{
"name": "Michell Anderson",
"job": "Line Cook",
"city": "Mississauga",
}
]
How would I extract the second part of the dictionary from the first in order to only have the information on the right be in a new dictionary?
Quick Answer:
employees is a list of dictionaries so you can just directly index the list to get Michell:
newDict = employees[1]
More Detailed Answer:
Firstly, here is how you create a key-value pair in a dictionary:
dct = {}
dct['color'] = 'blue' # dct = {'color':'blue'}
Knowing this, all you would need to copy a dictionary is the keys and values. You can use the .keys(),.values(), and .items() methods of dictionaries to do this.
dct.keys() # returns a list of all the keys -> ['color']
dct.values() # returns a list of all the values -> ['blue']
dct.items() # return a list of all the pairs as tuples -> [('color','blue')]
There are other options to copy as another user has mentioned however I strongly suggest you get used to work with the 3 methods listed above. If you haven't already, make sure you are really comfortable with lists before you jump into dictionaries and combined structures. You already seem to know how to work loops so hopefully this is helpful enough, good luck!
You have them backwards; the outer one [] is a list. The inner ones {} are dictionaries.
You can get the second one with employees[1] (indexing starts from 0) or the last one with employees[-1] (in this case they are the same).
If you need a copy, you can call .copy() on the result:
second_employee = employees[1]
copied_details = second_employee.copy()

LEFT JOIN dictionaries in python based on value

#Input
dict_1 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.250"}}
dict_2 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.252"}}
#Mapper can be modified as required
mapper = {"10.10.210.250":"black","192.168.2.1":"black"}
I am getting each dict in a loop, in each iteration I need to check a dict against the mapper and append a flag based on match between dict_1.orig_h and mapper.10.10.210.250 . I have the flexibility to define the mapper however I need.
So the desired result would be:
dict_1 = {"conn": {"ts":15,"uid":"ABC","orig_h":"10.10.210.250", "class":"black"}}
dict_2 will remain unchanged since there is no matching value in mapper.
This is kinda what I want, but it works only if orig_h is an int
import collections
result = collections.defaultdict(dict)
for d in dict_1:
result[d[int('orig_h')]].update(d)
for d in mapper:
result[d[int('orig_h')]].update(d)
Not much explaining to be done; if the ip is in the mapper dictionary (if mapper has a key which is that ip) then set the desired attribute of the dict to the value of the key in the mapper dict ('black' here).
def update_dict(dic, mapper):
ip = dic['conn']['orig_h']
if ip in mapper:
dic['conn']['class'] = mapper[ip]
which works exactly as desired:
>>> update_dict(dict_1, mapper)
>>> dict_1
{'conn': {'ts': 15, 'uid': 'ABC', 'orig_h': '10.10.210.250', 'class': 'black'}}
>>> update_dict(dict_2, mapper)
>>> dict_2
{'conn': {'ts': 15, 'uid': 'ABC', 'orig_h': '10.10.210.252'}}
Extracting the conn value for simplicity:
conn_data = dict_1['conn']
conn_data['class'] = mapper[conn_data['orig_h']]
A two liner, extracting class and dict if the 'orig_h' is in the mapper dictionary's keys, if it id, keep it, otherwise don't keep it, then create a new dictionary comprehension inside the list comprehension to add 'class' to the dictionary's 'conn' key's dictionary.
l=[(i,mapper[i['conn']['orig_h']]) for i in (dict_1,dict_2) if i['conn']['orig_h'] in mapper]
print([{'conn':dict(a['conn'],**{'class':b})} for a,b in l])
BTW this answer chooses the dictionaries automatically

How to get dict value x via dict value y from list of dicts

(Python 2.x) A list of dicts with only unique key-value pairs, sorted alfabetically by name, names are unique as well:
dictlist = [
{'name': 'Monty', 'has': 'eggs'},
{'name': 'Terry', 'has': 'bacon'}
]
I want to get what a given name has, by name. The following works.
names = ['Monty', 'Terry']
print dictlist[names.index('Terry')]['has']
I've made a parallel list with just names in the same order as the names in the dictlist, so I can make use of the order of the list. (I could fill names with a for loop, but that's not relevant here).
From here, among others, I know I could do this:
print next((d['has'] for d in dictlist if d['name'] == 'Terry'), None)
but that's only better if dictlist isn't sorted by name.
So I'm wondering if there isn't a more concise way of doing this, preferably one that's at least as readable as the first method?
I would not use a list at all. I would use a dictionary instead.
dictlist = {
'Monty': {'has': 'eggs'},
'Terry': {'has': 'bacon'}
}
This allows you to look up values by name like so: dictlist['Monty']['has']
If you must use a list then I think you have a good solution as-is.

How to append to a list in a dictionary?

Can I append to a list in a dictionary?
test = {'food' : 'apple'}
Is there a command to add 'banana' and turn it into
test = { 'food': ['apple','banana'] }
Thank you
No, since it isn't a list in the first place.
test['food'] = [test['food'], 'banana']
You need to create a dict where the values are lists:
test = {'food' : ['apple']}
test['food'].append('banana')
The simplest solution would just be to just make the value of your hash a list, that may contain just one element. Then for example, you might have something like this:
test = {'food' : ['apple']}
test['food'].append('banana')
I'd recommend using a defaultdict in this case, it's pretty straightforward to deal with dictionaries of lists, since then you don't need two separate cases every time you modify an entry:
import collections
test = collections.defaultdict(list)
test['food'].append('apple')
test['food'].append('banana')
print test
# defaultdict(<type 'list'>, {'food': ['apple', 'banana']})

Appending something to a list within a dict within a list in Python

I am attempting to create a list of dicts which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
Initially, this list will be empty.
What I need to be able to do is:
Check to see if a dict with a specific id exists in the list already
If a dict containing that id exists, append something to it's embedded_list
If a dict containing that id does not exist, create a dict, append it to the list.
I am aware of being able to test if a dict exists in a list based on something inside that dict using something like this:
extracted_dict = next((item for item in list if item['id'] == unique_id), None)
I am unsure of how to append something to a list within a dict within a list efficiently. Is there an obvious way which I'm not seeing (probably)?
Thank you in advance.
Your data structure should be a dictionary of dictionaries in the first place:
{'234nj233nkj2k4n52': {'embedded_list': []},
'jb234bhj23423h4b4': {'embedded_list': []},
... }
This will make all your desired operations much easier. If the inner dictionaries only contain the embedded list, this can be further simplified to
{'234nj233nkj2k4n52': [],
'jb234bhj23423h4b4': [],
... }
Now, all you need is a collections.defaultdict(list):
from collections import defaultdict
d = defaultdict(list)
d['234nj233nkj2k4n52'].append(whatever)
or just a simple dic
{
'234nj233nkj2k4n52' : [],
'jb234bhj23423h4b4' : []
}

Categories