How to update a Python dictionary with a reference dictionary the Pythonic way? - dictionary

I think it is pretty straightforward. All I am trying to do is update the original dictionary's 'code' with that of another dictionary which has the value. I get a feeling 2 for loops and an IF loop can be further shortened to get the answer. In my actual problem, I have few 1000's of dicts that I have to update. Thanks guys!
Python:
referencedict = {'A': 'abc', 'B': 'xyz'}
mylistofdict = [{'name': 'John', 'code': 'A', 'age': 28}, {'name': 'Mary', 'code': 'B', 'age': 32}, {'name': 'Joe', 'code': 'A', 'age': 43}]
for eachdict in mylistofdict:
for key, value in eachdict.items():
if key == 'code':
eachdict[key] = referencedict[value]
print mylistofdict
Output:
[{'age': 28, 'code': 'abc', 'name': 'John'}, {'age': 32, 'code': 'xyz', 'name': 'Mary'}, {'age': 43, 'code': 'abc', 'name': 'Joe'}]

There is no need to loop over all values of eachdict, just look up code directly:
for eachdict in mylistofdict:
if 'code' not in eachdict:
continue
eachdict['code'] = referencedict[eachdict['code']]
You can probably omit the test for code being present, your example list always contains a code entry, but I thought it better to be safe. Looking up the code in the referencedict structure assumes that all possible codes are available.
I used if 'code' not in eachdict: continue here; the opposite is just as valid (if 'code' in eachdict), but this way you can more easily remove the line if you do not need it, and you save yourself an indent level.

referencedict = {'A': 'abc', 'B': 'xyz'}
mylistofdict = [{'name': 'John', 'code': 'A', 'age': 28}, {'name': 'Mary', 'code': 'B', 'age': 32}, {'name': 'Joe', 'code': 'A', 'age': 43}]
for x in mylistofdict:
try:
x['code']=referencedict.get(x['code'])
except KeyError:
pass
print(mylistofdict)

Related

Is there a place to report API data errors for the HERE browse search API?

When using requests.get('https://browse.search.hereapi.com/v1/browse?apiKey=' + YOUR_API_KEY + '&at=53.544348,-113.500571&circle:46.827727",-114.000519,r=3000&limit=10&categories=800-8200-0174') I get a response that shows Canadian postal codes - but only the first 3 characters.
For example, I get this data:
{'title': 'Boyle Street Education Centre', 'id': 'here:pds:place:124c3x29-d6c9cbd3d53a4758b8c953132db92244', 'resultType': 'place', 'address': {'label': 'Boyle Street Education Centre, 10312 105 St NW, Edmonton, AB T5J, Canada', 'countryCode': 'CAN', 'countryName': 'Canada', 'stateCode': 'AB', 'state': 'Alberta', 'county': 'Alberta', 'city': 'Edmonton', 'district': 'Downtown', 'street': '105 St NW', 'postalCode': 'T5J', 'houseNumber': '10312'}, 'position': {'lat': 53.54498, 'lng': -113.5016}, 'access': [{'lat': 53.54498, 'lng': -113.50105}], 'distance': 98, 'categories': [{'id': '800-8200-0174', 'name': 'School', 'primary': True}, {'id': '800-8200-0295', 'name': 'Training & Development'}], 'references': [{'supplier': {'id': 'core'}, 'id': '36335982'}, {'supplier': {'id': 'yelp'}, 'id': 'r3BvVKqluzrZeae9FE4tAw'}], 'contacts': [{'phone': [{'value': '+17804281420'}], 'fax': [{'value': '(780) 429-1458', 'categories': [{'id': '800-8200-0174'}]}], 'www': [{'value': 'http://www.bsec.ab.ca', 'categories': [{'id': '800-8200-0174'}]}]}], 'openingHours': [{'categories': [{'id': '800-8200-0174'}], 'text': ['Mon-Sat: 09:00 - 17:00', 'Sun: 10:00 - 16:00'], 'isOpen': False, 'structured': [{'start': 'T090000', 'duration': 'PT08H00M', 'recurrence': 'FREQ:DAILY;BYDAY:MO,TU,WE,TH,FR,SA'}, {'start': 'T100000', 'duration': 'PT06H00M', 'recurrence': 'FREQ:DAILY;BYDAY:SU'}]}]}
Notice that the postal code listed is "T5J". This is incorrect. Canadian postal codes are 3 characters, a space, and then 3 more characters. I'm guessing this is a parsing error that occurred when the data was captured. The correct postal code is "T5J 1E6".
Yes, HERE has a tool to modify the poi address information.
I reported this poi postal code to be updated to "T5J 1E6".
Please visit below the web tool.
https://mapcreator.here.com/place:124c3x29-d6c9cbd3d53a4758b8c953132db92244/?l=53.5450,-113.5016,18,normal
Thank you!

How to Add multiple nested Dictionaries

dicta={'name': 'C','children': {'name': 'testA','children': {'name': 'test_file'}}}
dictb={'name': 'C','children': {'name': 'testA','children': {'name': 'test_fileB','children': {'name': 'test_file'}}}}
dictc={'name': 'C','children':[{"name":"testA","children":[{"name":"test_file"},{'name': 'test_fileB','children': {'name': 'test_file'}}]}]}
I want to use dicta and dictb to get dictc;but I don't know how.
You can define a function to merge dictionaries and call it recursively:
def merge(dict1, dict2):
result = {**dict1}
if 'children' in dict1 and 'children' in dict2:
if dict1['children']['name'] == dict2['children']['name']:
result['children'] = [merge(dict1['children'], dict2['children'])]
else:
result['children'] = [dict1['children'], dict2['children']]
elif 'children' in dict1:
result['children'] = [dict1['children']]
elif 'children' in dict2:
result['children'] = [dict2['chidlren']]
else:
del result['children']
return result
dictc = merge(dicta, dictb)
You didn't provide many details on how exactly the merge should work, but this example does produce the dictc as you want. You may need to tweak something for your needs

Strip out quotation marks that are found inside quotes using R

I have some data that is in almost-JSON format, but not quite. I'm trying to convert it from JSON using jsonlite in R. Here is a sample of data:
field
{'email': {'name': 'Bob Smith', 'address': 'bob_smith#blah.com'}}
{'email': {'name': "Sally O'Mally", 'address': 'sally_omally#blah.com'}}
{'email': {'name': 'Sam Daniels', 'address': '"some text"<sam_daniels#xyz.com>'}}
{'email': {'name': "Johnson', Alan", 'address': 'alan.johnson#abc.com'}}
What I want to do is strip out all of the quotation marks (both single and double) that are inside of the main quotations. The data would then look like this:
field
{'email': {'name': 'Bob Smith', 'address': 'bob_smith#blah.com'}}
{'email': {'name': "Sally OMally", 'address': 'sally_omally#blah.com'}}
{'email': {'name': 'Sam Daniels', 'address': 'some text<sam_daniels#xyz.com>'}}
{'email': {'name': "Johnson, Alan", 'address': 'alan.johnson#abc.com'}}
After that, I can handle converting the single quotes to double quotes using stringr and convert from JSON.
Any suggestions?
This is the error I currently get when trying to convert the original data from JSON:
> json_test2 <-
+ json_test %>%
+ dplyr::mutate(
+ field2 = map(field, ~ fromJSON(.) %>% as.data.frame())
+ )
Error: lexical error: invalid char in json text.
{'email': {'name': 'Bob S
(right here) ------^

vis.js network: nodes z-index

Is there an equivalent of the CSS z-index for vis.js nodes?
Suppose that I have 2 kinds of nodes (in a graph with physics disabled): Circles and rectangles. I would like the rectangles to always be displayed over the circles when they are overlapping.
Kind of a late reply but the short answer is: no
See this issue: https://github.com/almende/vis/issues/3146
Judging by the mentioned issue, a more precise answer would be: there's no documented way to set z-index (and there's no such concept), but what you can use (with a risk of getting this broken at some update) is nodes are drawn in the same order they are defined. From comment:
I used the following test nodes:
var nodes = [
{id: 'a', label: 'a', shape: 'dot'},
{id: 'b', label: 'b', shape: 'dot'},
{id: 'c', label: 'c', shape: 'dot'},
{id: 'd', label: 'd', shape: 'dot'}
];
When not selected, these will draw in the node order:
Now, let's change the order:
var nodes = [
{id: 'c', label: 'c', shape: 'dot'},
{id: 'b', label: 'b', shape: 'dot'},
{id: 'd', label: 'd', shape: 'dot'},
{id: 'a', label: 'a', shape: 'dot'}
];

Filter Dictionary using key and Value in list in Python

I am new to python and trying to filter a dictionary from list using value and key. I am using python 3
[{'ctime': 1459426422, 'accesskey': 'xxxxxx', 'secretkey': 'xxxx', 'id': 4, 'fsname': '/mnt/cdrom1', 'name': '/mnt/cdrom1:test1'}, {'ctime': 1459326975, 'accesskey': 'xxxx', 'secretkey': 'xxxx', 'id': 1, 'fsname': '/mnt/cdrom2', 'name': '/mnt/cdrom2:test2'}]
From above output, I need to filter a dictionary with key value as 'name':'/mnt/cdrom2:test2' so I get fitered dictionary as
{'ctime': 1459326975, 'accesskey': 'xxxx', 'secretkey': 'xxxx', 'id': 1, 'fsname': '/mnt/cdrom2', 'name': '/mnt/cdrom2:test2'}
I can then later extract keys and values as needed.
Thanks.
If your above list is in a variable named "my_list"
Python 2.7.x Version
for d in my_list:
if d['name'] == '/mnt/cdrom2:test2':
print d['name'] # or do whatever you want here
Python 3 Version
for d in my_list:
if d['name'] == '/mnt/cdrom2:test2':
print(d['name']) # or do whatever you want here

Resources