Accessing elements in dictionary of dictionaries - python

I am parsing some information from a CSV File and am inputting it into a dict of dicts. The inner dict v contains the following elements {'140725AD4': <mod.City object at 1x3259C2D1>, '631315AD2': <mod.City object at 0x023A4870>}. How would I access the object <mod.city object at 0x0138C3B0> for example?
Thank You.

Having a structure like the following:
john = {
"name": "John",
"family": {
"son": "Ret",
"daughter": "Pat"
}
}
You can access the John son's name like this:
john['family']['son']
This will return "Ret"
In your case, if City object is a DICT you can use:
dict['140725AD4']['population']
If your City object is just a Class you can do
dict['140725AD4'].getPopulation()
or
dict['140725AD4'].population
How it works?
A dictionary is a hashmap of pairs (name, value). Whenever you call a name the value is given. In Python, the value can be anything, from int to a Class.
So when in a dict you ask for a name inside a dict like dict['name'] you get back the value associated with it. In this case its your City object. Then you can call anything related to the value: functions, variables...

Assuming this question is the follow up for this one - Updating Dictionary of Dictionaries in Python you would have to do this:
inner_dict = places["City"]
for _, city_obj in inner_dict.items():
print city_obj.population # Assuming population is one of the member variables of the class mod.city

Related

LIST DESCRIPTION NOT WORKING WITH DICTIONARY (PYTHON)

#python
pets=[] #created an empty list
d={'owner_name': 'holland',
'pet_kind':'mischieveous',
}
d={'owner_name': 'rowman',
'pet_kind':'smart',
}
d={'owner_name': 'clark',
'pet_kind':'happy'
}
d={'owner_name': 'shaun',
'pet_kind':'shy',
}
d={'owner_name': 'seaman',
'pet_kind':'intellectual',
}
pets=[pets.append(pet) for pet in d.items()]
print(pets)
output is showing [None, None] , I believe it should show the dictionary #appended in pets but it is not please help a newbie here .. please
for pet in d.items():
pets.append(pet)
print(pets)
also if i use the for loop the second way it still gives me only the last dictionary as answer, the seaman and intellectual one, i am hopeful to learn this lang please help
here i have included the second way above please check
What are you trying to achieve? Is this just homework?
You can simply create a list of dicts to get the same result:
pets = [{'owner_name': 'holland', 'pet_kind':'mischieveous'},
{'owner_name': 'rowman', 'pet_kind':'smart'},
{'owner_name': 'clark', 'pet_kind':'happy'},
{'owner_name': 'shaun', 'pet_kind':'shy'},
{'owner_name': 'seaman', 'pet_kind':'intellectual'}]
This code would do the work:
d = {
"owner_name": "seaman",
"pet_kind": "intellectual",
}
pets=[pet for pet in d.items()]
print(pets)
the second way you said has a problem that is because you named all your variables "d". they overwrite each other.
Firstly, the list comprehension:
pets = [pets.append(pet) for pet in d.items()]
This syntax collects the results of the method call pets.append(...) in a list, then assigns it to the variable pets. However, pets.append(...) does not return anything — it modifies the list in place — so that will collect a list of None values as returned from each call of the method.
The method will append it to pets in-place, but then the assignment operator will overwrite pets with the list of None values, which you're seeing.
Secondly, the assignments:
d = {
'owner_name': 'holland',
'pet_kind': 'mischievous',
}
d = {
'owner_name': 'rowman',
'pet_kind': 'smart',
}
...
These will assign different values to the same variable d, just like writing:
x = 1
x = 2
...
Finally, the .items() method
for pet in d.items():
This method is applicable to a dictionary, not a list; it turns that dictionary into a list of pairs, so within the loop, the variable pet will have the value ('owner_name', 'seaman') the first time through the loop and then ('pet_kind', 'intellectual') the second time through the loop.
As a side-note, it's often more convenient to "unpack" those pairs into a pair of variables, like this:
for key, value in d.items():

How to use map() with dictionary comprehension in Python

I am trying to use map() on a list of dictionaries to get a name and id only.
My input:
employees = [
{"id": 12113, "name": "Jim", "department": "Sales"},
{"id": 12342, "name": "Michael", "department": "Management"},
{"id": 23312, "name": "Dwight", "department": "Sales"},
]
What I want my function to return is a dictionary where each key is the employee's name and the value is the employee's ID.
My function currently contains what is below but isn't returning values, only: <map object at 0x7f3b0bb6d460>, <map object at 0x7f78e7242670>.
My code:
def name_id(employees):
name_and_ids = [{map(('name', 'id'), emp) for emp in employees}]
print(list(name_id)) ### to see if what I want is being output or not
return name_and_ids
I am calling my function with:
print(f"Name and ids: {name_id(employees)}")
I am fairly new to python and am getting confused with comprehensions in general, whether list or dictionary comprehensions. I did see you can use dict and/or zip but would like to learn something new with map().
Any advice/help to push me in the right direction of getting what I want would be much appreciated.
What I want my function to return is a dictionary where each key is the employee's name and the value is the employee's ID.
You need a dictionary comprehension:
result = {
emp['name']: emp['id']
for emp in employees
}
map is not an appropriate tool for the job, because it converts N things to N other things, whereas you need to convert N things (3 employees) into one thing (a dict). If you insist, you could use map to convert the source list into a list of key-value tuples and then apply dict to the result:
from operator import itemgetter
result = dict(
map(itemgetter('name', 'id'), employees)
)
This style is not considered "pythonic" though.
The map function doesn't do anything related to what you want here. It's leading you astray.
Instead, just do the mapping you want yourself in the dict comprehension you already have:
name_and_ids = {emp['name']: emp['id'] for emp in employees}

How to iterate over attribute names of an custom object

Hi I have a JSON Object in my python code and I use them as object in my code. Its type is JSONHelper.X which is a custom class I wrote which reads a json file and transform its to a object for using easily.
{
"Gui":{
"Images":{
"Logo1":"url1",
"Logo2":"url2",
"Logo3":"url3",
"Logo4":"url4",
"Logo5":"url5"
}
}
}
How can I retrive pair of attribute name and value from this object to give another class as parameter. JSONHelper object does not seem to have dict attribute so I can not say Gui.Images.keys(). When I print Gui.Images I only get values.
I can reach attribute names as below. Is there any better way to do this?
def prop_names(self):
l = []
public_props = (name for name in dir(self.settings.Images) if not name.startswith('_'))
for name in public_props:
if name is not "count" and name is not "index":
print(name)
print(l
)
output:
Logo1
Logo2
Logo3
Logo4
Logo5
Convert your JSON helper string into dictionary using json.load (see comments from Barmar). From there you can access the keys values that you want.
import json
import itertools
j="""{
"Gui":{
"Images":{
"Logo1":"url1",
"Logo2":"url2",
"Logo3":"url3",
"Logo4":"url4",
"Logo5":"url5"
}
}
}"""
d = json.loads(j)
l = [list(d[k1][k2].keys()) for k1 in d.keys() for k2 in d[k1].keys()]
print(list(itertools.chain.from_iterable(l)))
Result:
['Logo1', 'Logo2', 'Logo3', 'Logo4', 'Logo5']

how to access a dictionary key value in the other key of same dictionary

i am new to python and not getting a way to access the dictionary value in another key of same dictionary.
keys = {
'sample': some_data,
'sample2': keys['sample']
}
The above codeblock gives an TypeError: 'module' object is not subscriptable
Is there anything like this keyword in python to do so.
The keys dictionary doesn't exist when you reference it. You need to define it before referencing it.
This code runs just fine:
some_data = 'xxx'
keys = {
'sample': some_data,
}
keys['sample2'] = keys['sample']
print(keys['sample2'])
Output:
>>> xxx
If you look at your dictionary, you are trying to reference keys inside the keys dictionary itself. Which is impossible since you haven't defined keys in the first place (Circular reference).
The easiest way to avoid it to just do.
keys = {
'sample': some_data,
'sample2': some_data
}

Trying to grow a nested dictionary by adding more key:value pairs

I am facing some trouble with trying to add more key:value pairs to a dictionary object that is itself nested within another dictionary object. Also, the usual way of doing dict[key] = value to assign additional key:value pairs to the dictionary is not suitable for my case here (I'll explain why later below), and thus this makes my objective a lot more challenging to achieve.
I'll illustrate what I'm trying to achieve with some statements from my source code.
First, I have a dictionary object that contains nesting:
environment = { 'v' :
{
'SDC_PERIOD':'{period}s'.format(period = self.period),
'FAMILY':'{legup_family}s'.format(legup_family = self.legup_family),
'DEVICE_FAMILY':'"{fpga_family}s"'.format(fpga_family = self.fpga_family)
}
}
and then following this line, I will do an if test that, if passed, will require me to add this other dictionary:
environment_add = { 'v' : {'LM_LICENSE_FILE' : '1800#adsc-linux'} ,
'l' : 'quartus_full' }
to ultimately form this complete dictionary:
environment = { 'v' :
{
'SDC_PERIOD':'{period}s'.format(period = self.period),
'FAMILY':'{legup_family}s'.format(legup_family = self.legup_family),
'DEVICE_FAMILY':'"{fpga_family}s"'.format(fpga_family = self.fpga_family),
'LM_LICENSE_FILE' : '1800#adsc-linux'
} ,
'l' : 'quartus_full'
}
As you can see, if I were to try and assign a new key:value pair using the dict[key] = value syntax, it would not work for me because it would end up either creating an new key:value pair for me, or overwrite the existing dictionary object and the key:value pairs that are nested under the 'v' key.
So far, in order to accomplish the creation of the dictionary, I've been using the following:
environment = """{ v: {'SDC_PERIOD':'%(period)s','FAMILY':'%(legup_family)s','DEVICE_FAMILY':'"%(fpga_family)s"'}}""" % self
if self.require_license: # this is the if statement test that I was referring to earlier
environment = environment.replace('}', '')
environment += """ ,'LM_LICENSE_FILE':'1800#adsc-linux'}, 'l': 'quartus_full'}"""
and then obtaining the dictionary object later with:
import ast
env_dict = ast.literal_eval(environment)
which gives effectively converts the environment string into a dictionary object stored under a new variable name of env_dict.
My teammates think that this is much too overkill, especially since the environment or env_dict object will be parsed in 2 separate modules later on. In the first module, the key-value pairs will be broken up and reconstructed to form strings that look like '-v SDC_PERIOD=2500s, LM_LICENSE_FILE=1800#adsc-linux' , while in the second module, the dictionary nested under the 'v' key (of the environment/env_dict dictionary object) will be extracted out and directly fed as an argument to a function that accepts a mapping object.
So as you can see, there is quite a lot of precise parsing required to do the job, and although my method fulfills the objective, it is not accepted by my team and they think that there must be a better way to do this directly from environment being a dictionary object and not a string object.
Thank you very much for studying my detailed post, and I will greatly appreciate any help or suggestions to move forward on this!
for k,v in environment_add.iteritems(): # .items() in Python 3
if k in environment:
environment[k].update(v)
else:
environment[k] = v
That is, for each item to add, check if it exists, and update it if so, or simply create it. This assumes the items being added, if they exist, will be dicts (you can't update a string like quartus_full).
Why not just use update
In [4]: dict_ = {"a": {"b": 2, "c": 3}}
In [5]: dict_["a"].update(d=4)
In [6]: dict_
Out[6]: {'a': {'b': 2, 'c': 3, 'd': 4}}

Categories

Resources