Access value of dictionary output - python

I'm simply trying to access the output from a variable named parser which is outputting a dictionary of information in it like:
{u'param': [u'6'], u'booID': [u'911'], u'animal': [u'cat']}
How can I access each parameter, and loop through each outputting the key value?
I tried, a number of different things including:
for parsed_val in parser:
print parsed_val + parsed_val.keys()
but this throws a AttributeError of AttributeError: 'unicode' object has no attribute 'keys'.
Thank you!

for key, value in parser.iteritems():
print key, value

Iterating through a dictionary iterates through its keys.
You'll want to iterate over dict.items(), which iterates over a list of (key,pair) tuples.
You can also use dict.iteritems (on python 2.x), which avoids creating a list and iterates directly over the dictionary

Alternative method:
for key in parser.keys():
print(str(key) + ': '+str(parser[key]))
dict.keys() is a list of all keys.
dict.items() is a list of of key/value pairs.
dict.iteritems is an iterable object of dict.items().

Related

how to pass string as key in dictionary

i want to parse dictionary dynamically
here i'm trying to get the name of key dynamically and storing that key in variable and call dictionary using those variable
so far i tried this
var=users.to_dict()
z=var.keys()
y=z[0]
x=var[str(y)]['Scheme name']
when i pass str(y) it giving error
y=x[0]
TypeError: 'dict_keys' object does not support indexing
is there any better ways to this. please let me know
you cannot index 'dict_keys' but if you parse them to 'list'
var=users.to_dict()
z=list(var.keys())
y=z[0]
x=var[str(y)]['Scheme name']
it should work
y=z[0]
is where your error is.
var.keys() doesn't return a list, it returns a dict_keys, which doesn't support indexing. You can convert it to an list and then index:
y = list(x)[0]
However, z = list(var) will have the same effect (list of keys) and is a little more direct.
A dict_keys behaves this way because it's a view object. It's an iterable whose contents change if the underlying dictionary changes. The result of casting it as a list (or casting the dictionary as a list) is that it's no longer connected to dictionary.

python: getting keys of a dictionary

When I do dict.keys() in python3, I do not get a list, but an object of class dict_keys. Why is this and what can I do with this object? How to get the list?
Example code: type(dict(sape=4139, guido=4127, jack=4098).keys())
I wonder if this result is intentional and why?
I called matplotlib.plot(d.keys(),....) and got an error.
dict.keys returns a dict_keys object, which is an iterable object.
So, you can either convert it to a list using:
keys = list(dict.keys())
Or, you can simply iterate over the dict_keys object, like it was intended:
for key in dict.keys():
print(key)
In your example, it will print out:
sape
guido
jack

python 2.7 create dictionary key from tuple

How do I create an ordered dictionary key from a tuple in Python 2.7?
I have seen a lot of examples about creating a new dictionary from a tuple, or building tuples from dictionary keys but not how to generate a "multi-dimensional key" from a tuple, i.e. use the keys in the tuple to recursively index into a nested dictionary.
Basically I would like to use a tuple such as:
('australia', 'queensland', 'brisbane')
as a dictionary key:
places['australia']['queensland']['brisbane']
The dictionary is an OrderedDict that contains JSON data.
One liner (where t is your tuple and places is your dictionary of dictionaries of dictionaries of...):
reduce(dict.get, t, places)
What's actually happening here is that you're repeatedly getting each element of the tuple t from the dict places.
In python 3, you'll need to import reduce via from functools import reduce.

Delete an item from a python dictionary when two keys have the same value

I have a python dictionary which has two keys with the same value.
mydict = {'a':'hi','b':'bye','c':'hi'}
What do I do if I want to delete just the element 'c':'hi'
I tried both del mydict['c'] and mydict.pop('c',None). Both these give me a KeyError.
First of all, there won't be a difference when you assign the same value to multiple keys. All elements in a python dict are required to have unique, immutable keys but there is no such constraint on the value. So don't worry too much about that!
This aside, both of the options you proposed behave as intended. The KeyError being thrown means that the key 'c' is not present in the dictionary. This leads me to believe that what you have shown is not in the dictionary at the time when the del or pop is called.

List of dictionaries: get() schould loop over list

I know it is easy to implement.
I want a dictionary like class, which takes a list of dictionaries in the constructor.
If you read from this dict by key, the dict-class should check the list of dictionaries and return the first value. If none contains this key KeyError should be thrown like a normal dict.
This dictionary container should be read only for my usage.
You seem to be describing collections.ChainMap, which will be in the next version of Python (3.3, expected to go final later this year). For current/earlier versions of Python, you can copy the implementation from the collections source code.
Not really answer to the question: what if you just define method that merge all dictionaries into one? Why make new class for it?
How to merge: How to merge two Python dictionaries in a single expression?
Varargs: Can a variable number of arguments be passed to a function?
You can easily implement this with this logic.
Iterate over all the dictionaries in the list.
For each dictionary, see if it has the required key by using key in value statement.
If value is found, return the value from the function.
If you have iterated over all dictionaries, and value is not found, Raise KeyError exception.

Categories

Resources