I am trying to parse a json object and having problems.
import json
record= '{"shirt":{"red":{"quanitity":100},"blue":{"quantity":10}},"pants":{"black":{"quantity":50}}}'
inventory = json.loads(record)
#HELP NEEDED HERE
for item in inventory:
print item
I can figure out how to obtain the values. I can get keys. Please help.
You no longer have a JSON object, you have a Python dictionary. Iterating over a dictionary produces its keys.
>>> for k in {'foo': 42, 'bar': None}:
... print k
...
foo
bar
If you want to access the values then either index the original dictionary or use one of the methods that returns something different.
>>> for k in {'foo': 42, 'bar': None}.iteritems():
... print k
...
('foo', 42)
('bar', None)
import json
record = '{"shirts":{"red":{"quantity":100},"blue":{"quantity":10}},"pants":{"black":{"quantity":50}}}'
inventory = json.loads(record)
for key, value in dict.items(inventory["shirts"]):
print key, value
for key, value in dict.items(inventory["pants"]):
print key, value
Related
I'm trying to do a dictionary which include countries GMT time (int number)
for example I have a dict and I want to get the value of it, I tried this code:
countires= {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}
print(countires.get('Athens'))
and the output is:
None
How I can get result 2?
IIUC, You need create temp dict that have seperate key and search what you want like below:
>>> countires= {('Jerusalem', 'Athens', 'Bucharest'):2 ,('Bahrain','Qatar'):3}
>>> dct = {k:value for key,value in countires.items() for k in key}
>>> print(dct.get('Athens'))
2
If you want to use your original dictionary you can define function and search in keys like below:
>>> def search_multi_key(search, dct):
... for key, value in dct.items():
... if search in key:
... return value
... return None
>>> search_multi_key('Athens', countires)
2
One approach is to create a new dictionary, that uses as key each of the elements of the tuples:
countries= {('Jerusalem', 'Athens', 'Bucharest'):2 , ('Bahrain', 'Qatar'):3}
cities = { key : value for keys, value in countries.items() for key in keys }
print(cities.get('Athens'))
Output
2
if there is a dictionary:
dict={'a':'b'}
in python 3, i would like to convert this dictionary key to a string and its value to another string:
print(key)
key='a'
print(type(key))
str
print(value)
value='a'
print(type(value))
str
Some attempts:
str(dict.key()) # returns 'dict' object has no attribute 'key'
json.dump(dict) # returns {'a':'b'} in string, but hard to process
Any easy solution? Thank you!
Use dict.items():
You can use dict.items() (dict.iteritems() for python 2), it returns pairs of keys and values, and you can simply pick its first.
>>> d = { 'a': 'b' }
>>> key, value = list(d.items())[0]
>>> key
'a'
>>> value
'b'
I converted d.items() to a list, and picked its 0 index, you can also convert it into an iterator, and pick its first using next:
>>> key, value = next(iter(d.items()))
>>> key
'a'
>>> value
'b'
Use dict.keys() and dict.values():
You can also use dict.keys() to retrieve all of the dictionary keys, and pick its first key. And use dict.values() to retrieve all of the dictionary values:
>>> key = list(d.keys())[0]
>>> key
'a'
>>> value = list(d.values())[0]
>>> value
'b'
Here, you can use next(iter(...)) too:
>>> key = next(iter(d.keys()))
>>> key
'a'
>>> value = next(iter(d.values()))
'b'
Ensure getting a str:
The above methods don't ensure retrieving a string, they'll return whatever is the actual type of the key, and value. You can explicitly convert them to str:
>>> d = {'some_key': 1}
>>> key, value = next((str(k), str(v)) for k, v in d.items())
>>> key
'some_key'
>>> value
'1'
>>> type(key)
<class 'str'>
>>> type(value)
<class 'str'>
Now, both key, and value are str. Although actual value in dict was an int.
Disclaimer: These methods will pick first key, value pair of dictionary if it has multiple key value pairs, and simply ignore others. And it will NOT work if the dictionary is empty. If you need a solution which simply fails if there are multiple values in the dictionary, #SylvainLeroux's answer is the one you should look for.
To have a solution with several keys in dict without any import I used the following light solution.
dict={'a':'b','c':'d'}
keys = "".join(list(dict.keys()))
values = "".join(list(dict.values()))
>>> d = { 'a': 'b' }
>>> d.items()
dict_items([('a', 'b')])
At this point, you can use a destructuring assignement to get your values:
>>> [[key, value]] = d.items()
>>> key
'a'
>>> value
'b'
One advantage in this solution is it will fail in case of d containing several entries, instead of silently ignoring the issue.
>>> d = { 'a': 'b', 'c':'d' }
>>> [[key, value]] = d.items()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 1)
Finally, if you need to ensure key and value to be strings, you may add a list comprehension:
>>> d = { 1: 2 }
>>> [[key, value]] = ((str(key), str(value)) for key,value in d.items())
>>> key
'1'
>>> value
'2'
Make lists of keys and values:
dict={'a':'b'}
keys = list(dict.keys())
values = list(dict.values())
then make variables:
key = keys[0]
value = values[0]
https://docs.python.org/3/library/stdtypes.html#typesmapping
The methods are you looking for are keys() and values().
(I'm new to Python!)
Trying to figure out this homework question:
The function will takes as input two dictionaries, each mapping strings to integers. The function will return a dictionary that maps strings from the two input dictionaries to the sum of the integers in the two input dictionaries.
my idea was this:
def add(dicA,dicB):
dicA = {}
dicB = {}
newdictionary = dicA.update(dicB)
however, that brings back None.
In the professor's example:
print(add({'alice':10, 'Bob':3, 'Carlie':1}, {'alice':5, 'Bob':100, 'Carlie':1}))
the output is:
{'alice':15, 'Bob':103, 'Carlie':2}
My issue really is that I don't understand how to add up the values from each dictionaries. I know that the '+' is not supported with dictionaries. I'm not looking for anyone to do my homework for me, but any suggestions would be very much appreciated!
From the documentation:
update([other])
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.
You don't want to replace key/value pairs, you want to add the values for similar keys. Go through each dictionary and add each value to the relevant key:
def add(dicA,dicB):
result = {}
for d in dicA, dicB:
for key in d:
result[key] = result.get(key, 0) + d[key]
return result
result.get(key, 0) will retrieve the value of an existing key or produce 0 if key is not yet present.
First of all, a.update(b) updates a in place, and returns None.
Secondly, a.update(b) wouldn't help you to sum the keys; it would just produce a dictionary with the resulting dictionary having all the key, value pairs from b:
>>> a = {'alice':10, 'Bob':3, 'Carlie':1}
>>> b = {'alice':5, 'Bob':100, 'Carlie':1}
>>> a.update(b)
>>> a
{'alice': 5, 'Carlie': 1, 'Bob': 100}
It'd be easiest to use collections.Counter to achieve the desired result. As a plus, it does support addition with +:
from collections import Counter
def add(dicA, dicB):
return dict(Counter(dicA) + Counter(dicB))
This produces the intended result:
>>> print(add({'alice':10, 'Bob':3, 'Carlie':1}, {'alice':5, 'Bob':100, 'Carlie':1}))
{'alice': 15, 'Carlie': 2, 'Bob': 103}
The following is not meant to be the most elegant solution, but to get a feeling on how to deal with dicts.
dictA = {'Alice':10, 'Bob':3, 'Carlie':1}
dictB = {'Alice':5, 'Bob':100, 'Carlie':1}
# how to iterate through a dictionary
for k,v in dictA.iteritems():
print k,v
# make a new dict to keep tally
newdict={}
for d in [dictA,dictB]: # go through a list that has your dictionaries
print d
for k,v in d.iteritems(): # go through each dictionary item
if not k in newdict.keys():
newdict[k]=v
else:
newdict[k]+=v
print newdict
Output:
Bob 3
Alice 10
Carlie 1
{'Bob': 3, 'Alice': 10, 'Carlie': 1}
{'Bob': 100, 'Alice': 5, 'Carlie': 1}
{'Bob': 103, 'Alice': 15, 'Carlie': 2}
def add(dicA,dicB):
You define a function that takes two arguments, dicA and dicB.
dicA = {}
dicB = {}
Then you assign an empty dictionary to both those variables, overwriting the dictionaries you passed to the function.
newdictionary = dicA.update(dicB)
Then you update dicA with the values from dicB, and assign the result to newdictionary. dict.update always returns None though.
And finally, you don’t return anything from the function, so it does not give you any results.
In order to combine those dictionaries, you actually need to use the values that were passed to it. Since dict.update mutates the dictionary it is called on, this would change one of those passed dictionaries, which we generally do not want to do. So instead, we use an empty dictionary, and then copy the values from both dictionaries into it:
def add (dicA, dicB):
newDictionary = {}
newDictionary.update(dicA)
newDictionary.update(dicB)
return newDictionary
If you want the values to sum up automatically, then use a Counter instead of a normal dictionary:
from collections import Counter
def add (dicA, dicB):
newDictionary = Counter()
newDictionary.update(dicA)
newDictionary.update(dicB)
return newDictionary
I suspect your professor wants to achieve this using more simple methods. But you can achieve this very easily using collections.Counter.
from collections import Counter
def add(a, b):
return dict(Counter(a) + Counter(b))
Your professor probably wants something like this:
def add(a, b):
new_dict = copy of a
for each key/value pair in b
if key in new_dict
add value to value already present in new_dict
else
insert key/value pair into new_dict
return new_dict
You can try this:
def add(dict1, dict2):
return dict([(key,dict1[key]+dict2[key]) for key in dict1.keys()])
I personally like using a dictionary's get method for this kind of merge:
def add(a, b):
result = {}
for dictionary in (a, b):
for key, value in dictionary.items():
result[key] = result.get(key, 0) + value
return result
I have list which have keys of dictionary. How to access the dictionary using these keys dynamically. e.g
key_store = ['test','test1']
mydict = {"test":{'test1':"value"},"test3":"value"}
So how to access mydict using key_store I want to access mydict['test']['test1'].
Note: key_store store depth of keyword means it have keywords only its value will be dictionary like test have dictionary so it have 'test','test1'
You can do this with a simple for-loop.
def get_nested_key(keypath, nested_dict):
d = nested_dict
for key in keypath:
d = d[keypath]
return d
>>> get_nested_key(('test', 'test1'), Dict)
Add error checking as required.
Use recursion:
def get_value(d, k, i):
if not isinstance(d[k[i]], dict):
return d[k[i]]
return get_value(d[k[i]], k, i+1)
The parameters are the dictionary, the list and an index you'll be running on.
The stop condition is simple; Once the value is not a dictionary, you want to return it, otherwise you continue to travel on the dictionary with the next element in the list.
>>> key_store = ['test','test1']
>>> Dict = {"test":{'test1':"value"},"test3":"value"}
>>> def get_value(d, k, i):
... if isinstance(d[k[i]], str):
... return d[k[i]]
... return get_value(d[k[i]], k, i+1)
...
>>> get_value(Dict, key_store, 0)
'value'
You could do this with a simple dictionary reduce:
>>> mydict = {"test": {'test1': "value"}, "test3": "value"}
>>> print reduce(dict.get, ['test', 'test1'], mydict)
value
Is a dictionary the right type for data where I want to look up entries based on an index, e.g.
dictlist = {}
dictlist['itemid' + '1'] = {'name':'AAA', 'class':'Class1', 'nonstandard':'whatever'}
dictlist['itemid' + '2'] = {'name':'BBB', 'class':'Class2', 'maynotbehere':'optional'}
dictlist['itemid' + '3'] = {'name':'CCC', 'class':'Class3', 'regular':'or not'}
I can now address a specific item, e.g.
finditem='itemid2'
dictitem = {}
try:
dictitem[finditem] = dictlist[finditem]
print dictitem
except KeyError:
print "Nothing there"
Is that the right way to create such a lookup table in python?
If I now wanted to print the data, but only the Item ID, and an associated dictionary with only name and class "properties", how can I do that?
I am looking for something that will create a new dictionary by copying the desired properties only, or else present a limited view of the existing dictionary, as if the unspecified properties were not there. So for example
view(dictlist, 'name', 'class')
will return a dictionary that displays a restricted view of the list, showing only the name and class keys. I have tried
view = {}
for item in dictlist:
view[item] = {dictlist[item]['name'], dictlist[item]['class']}
print view
Which returns
{'itemid1': set(['AAA', 'Class1']), 'itemid3': set(['Class3', 'CCC']), 'itemid2': set(['Class2', 'BBB'])}
Instead of
{'itemid1': {'name':'AAA', 'class':'Class1'}, 'itemid3': {'name':'CCC', 'class':'Class3'}, 'itemid2': {'name':'BBB', 'class':'Class2'} }
Note that {'foo', 'bar'} is a set literal, not a dictionary literal, as it does not have the key: value syntax required for a dictionary:
>>> type({'foo', 'bar'})
<class 'set'>
>>> type({'foo': 'bar'})
<class 'dict'>
You need to be more careful with your syntax generally; I have no idea what the random closing square brackets ] are doing in the output you claim you want, and it's missing a closing brace }.
You could extend your current code to do keys and values as follows:
for item in dictlist:
view[item] = {'name': dictlist[item]['name'],
'class': dictlist[item]['class']}
but a more generic function would look like:
def view(dictlist, *keys):
output = {}
for item in dictlist:
output[item] = {}
for key in keys:
output[item][key] = dictlist[item].get(key)
return output
note the use of dict.get to handle missing keys gracefully:
>>> d = {'foo': 'bar'}
>>> d.get('foo')
'bar' # returns the value if key present, or
>>> d.get('baz')
>>> # returns None by default
or, using a "dictionary comprehension":
def view(dictlist, *keys):
return {k1: {k2: v2 for k2, v2 in v1.items() if k2 in keys}
for k1, v1 in dictlist.items()}
(This will exclude missing keys from the output, whereas the previous code will include them with None value - which is preferable will depend on your use case.)
Note the use of *keys to take an arbitrary number of positional arguments:
>>> def test(d, *keys):
print(keys)
>>> test({}, "foo", "bar", "baz")
('foo', 'bar', 'baz')