How to properly create a dictionary in Python - python

I am trying to create a dictionary in a function but I don't know for which reason I got this:
MONdic = {"mama"}
print MONdic
What I get as a result is :
set(['mama'])
Any help ?

dict is based on key value pairs (You have created a set)
d = {'key':'val'}

By default, if you pass an element or list of elements to {}, it will create a set.
But if you try passing key value pairs to {}, it will create a dictionary.
MONdic = {"key":"value"}, then the value of MONdic will be {"key":"value"}

dictionary must has keys and values
like:
my_dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
check https://www.w3schools.com/python/python_dictionaries.asp
for accessing it, changing values, loop it ..

But the problem is that I have a second dictionary that should merge with MONdic as in this example:
for key, value in results.items():
MONdic[key].extend(value)
To be able to merge these two dictionaries, they need to have the same keys. The values of MONdic should be empty in the beginning and I don't want to receive these kind of results if I do so :
MONdic = {"mama":[]}
for key, value in results.items():
MONdic[key].extend(value)
>>>> {"mama":[[1,2,5,9]]}

Related

Difficulty understanding changes to dictionary

I was looking through old posts in order to find a method of changing values in a dictionary by iterating through the items.
dictionary = {
1: [
{
"id": "1234",
"cow": "parts/sizes/lakes"
},
{
"id": "5151",
"cow": "minors/parts"
}
]}
def fetchanswers():
for item in dictionary[1]:
yield(item["id"], item["cow"])
for a, b in fetchanswers():
k = {}
k["id"] = a
k["cow"] = b.replace("parts", a)
My understanding is that yield returns the two items from either object in the dictionary and the for loop creates a new dictionary and appends the values obtained from fetchanswers() and parts is replaced by id.
I don't understand how k["id"] can be referred to when the dictionary is empty.
a method of changing values in a dictionary
Your values are strings. Strings are immutable, so you need to overwrite the dictionary using existing keys
You don't need another dictionary for this
# replace "parts" text value with the value of the id key
for item in list_of_dicts:
item["cow"] = item["cow"].replace("parts", str(item["id"]))
how k["id"] can be referred to
It's not a referral when there's an equal sign afterwards. It's an assignment

How can I extract a value from a list of dictionaries?

I have a dictionary:
dict = {
"Bolig":[
{
"Internal_id":27698,
"Title":"Thorshammer 95 7500 Holstebro",
"Area":87.0,
"Rent":6295.0,
"Room":4
}
],
"Contact":[
{
"Name":"John Doe",
"Email":"doe#gmail.com",
"Phone":"33751010212"
}
]
}
I want to extract the value of one of the keys : For example the value of the Internal_id key gives me the value 27698.
I tried to combine the dictionaries to a single dict by:
new_dict = {key: value for r in dict for key,value in r.iteritems()}
and extract but I got an error:
AttributeError: 'str' object has no attribute 'iteritems'
Is there a way I could achieve this?
for r in dict will iterate over the keys of the dictionary: "Bolig" and "Contact". So, r will be a string, and strings don't have the iteritems method (nor do dictionaries in Python 3 - you should be using items instead).
You should iterate over the stitched together values of dict:
import itertools
stitched_values = itertools.chain.from_iterable(dict.values())
result = {key: value for r in stitched_values for key, value in r.items()}
Or, if each value of the dictionary is guaranteed to be a list of one element:
result = {key: value for r in dict.values() for key, value in r[0].items()}
We need to target each layer one by one, the first is a dictionary so we use the key to target the nested dictionaries and in this case that is "Bolig" or "Contact". Then we use [ ] brackets to access the list and pass in an index. Then finally we target the attribute inside the innermost dictionary.
Now that we know how to access each dictionary and list you can understand how to automate this using loops.
x = dict['Bolig'][0]['Internal_id']
print(x) # 27698
In the dictionary comprehension
{key: value for r in dict for key,value in r.iteritems()}
r is the keys of dict, which in your case are strings. You can change this to
{key: value for r in dict.values() for key,value in r[0].items()}

Retrieve values from both nested dictionaries within a list

i'm using an api call in python 3.7 which returns json data.
result = (someapicall)
the data returned appears to be in the form of two nested dictionaries within a list, i.e.
[{name:foo, firmware:boo}{name:foo, firmware:bar}]
i would like to retrieve the value of the key "name" from the first dictionary and also the value of key "firmware" from both dictionaries and store in a new dictionary in the following format.
{foo:(boo,bar)}
so far i've managed to retrieve the value of both the first "name" and the first "firmware" and store in a dictionary using the following.
dict1={}
for i in result:
dict1[(i["networkId"])] = (i['firmware'])
i've tried.
d7[(a["networkId"])] = (a['firmware'],(a['firmware']))
but as expected the above just seems to return the same firmware twice.
can anyone help achive the desired result above
you can use defaultdict to accumulate values in a list, like this:
from collections import defaultdict
result = [{'name':'foo', 'firmware':'boo'},{'name':'foo', 'firmware':'bar'}]
# create a dict with a default of empty list for non existing keys
dict1=defaultdict(list)
# iterate and add firmwares of same name to list
for i in result:
dict1[i['name']].append(i['firmware'])
# reformat to regular dict with tuples
final = {k:tuple(v) for k,v in dict1.items()}
print(final)
Output:
{'foo': ('boo', 'bar')}

Filtering out Python Dictionary Values with Array of Nested Keys

I am trying to filter out a number of values from a python dictionary. Based on the answer seen here: Filter dict to contain only certain keys. I am doing something like:
new = {k:data[k] for k in FIELDS if k in data}
Basically create the new dictionary and care only about the keys listed in the FIELDS array. My array looks like:
FIELDS = ["timestamp", "unqiueID",etc...]
However, how do I do this if the key is nested? I.E. ['user']['color']?
How do I add a nested key to this array? I've tried:
[user][color], ['user']['color'], 'user]['color, and none of them are right :) Many of the values I need are nested fields. How can I add a nested key to this array and still have the new = {k:data[k] for k in FIELDS if k in data} bit work?
A quite simple approach, could look like the following (it will not work for all possibilities - objects in lists/arrays). You just need to specify a 'format' how you want to look for nested values.
'findValue' will split the searchKey (here on dots) in the given object, if found it searches the next 'sub-key' in the following value (assuming it is an dict/object) ...
myObj = {
"foo": "bar",
"baz": {
"foo": {
"bar": True
}
}
}
def findValue(obj, searchKey):
keys = searchKey.split('.')
for i, subKey in enumerate(keys):
if subKey in obj:
if i == len(subKey) -1:
return obj[subKey]
else:
obj = obj[subKey]
else:
print("Key not found: %s (%s)" % (subKey, keys))
return None
res = findValue(myObj, 'foo')
print(res)
res = findValue(myObj, 'baz.foo.bar')
print(res)
res = findValue(myObj, 'cantFind')
print(res)
Returns:
bar
True
Key not found: cantFind (cantFind)
None
Create a recursive function which checks whether the dictionary key has value or dictionary.
If key has dictionary again call function until you find the non-dictionary value.
When you find value just add it to your new created dictionary.
Hope this helps.

How to access values of dictionary when value contains another dictionary with multiple iterations on data?

my data is
my_dict = {
u'samosa': {
u'shape': u'triangle',
u'taste': None,
u'random': None,
u'salt': u'7.5.1'
},
u'idli': {
u'color': u'red',
u'eattime': u'134'
},
u'ridgegaurd': {},
u'sambhar': {
u'createdate': u'2016-05-12',
u'end time': u'10655437'
}
}
There are four keys samosa, idli, ridgegaurd and sambhar.
I don't want whole part of the values. I just want to get
value(shape) from samosa,
values(color and eattime) from idli
values(createdate and endtime) from sambhar
I want only the above values. I tried using dict but was not able to. Is it possible to write regular expressions for this?
If the value of a dictionary entry is another dictionary, you can simply index it again.
my_dict[u'samosa'][u'shape']
my_dict[u'idli'][u'color'], my_dict[u'idli'][u'eattime']
my_dict[u'sambhar'][u'createdate'], my_dict[u'sambhar'][u'endtime']
This function will recursively run through json and return a single dictionary with all the information, thus making it much easier to access your data:
def flatten(data):
flattened = {}
for k, v in data.items():
if isinstance(v, dict):
flattened.update(flatten(v))
else:
flattened[k] = v
return flattened

Categories