I have a dictionary of dictionaries that uses tuples as it's keys and values. I would like to write this dictionary and have tried json and pickle but neither of them seem to work. Is there a better alternative?
https://github.com/jgv7/markov-generator/blob/master/sentence-generator.py
json expects the key of the Key value pair to be a string or a number that can be properly converted to a string. bottom line - cant do a json.dumps on a dict with tuples as keys.
pickle should work unless the dictionary object is not properly serialized.
From your code:
with open(filename, 'rb') as df:
pickle.load(df)
print mapping
You don't bind the result of the load() call to a name, so that line has no effect (other than consuming processor time and moving the file pointer). That should read:
with open(filename, 'rb') as df:
mapping = pickle.load(df)
print mapping
Related
I read this page at W3Schools, and noticed it showed you can dump and sort by alphabetical order, is it possible to sort by the time?
My dump statement:
with open("./warns.json","w") as f:
json.dump(warns,f)
How would I dump it and sort it by date?
From https://docs.python.org/3/library/json.html#json.dump :
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.
Sorting by date is different, as it depends on the structure of your JSON. If you really need it, you can modify the encoder:
To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
This is used to serialize types, but you may be able to also control the output order.
Another solution is to use a sorted array in the JSON, to ensure the order is respected.
I have a dictionary full of unicode keys/values due to importing JSON through json.loads().
dictionaryName = {u'keyName' : u'valueName'}
I'm trying to access values inside the dictionary as follows:
accessValueName = dictionaryName.get('keyName')
This returns None, assumedly because it is looking for the String 'keyName' and the list is full of unicode values. I tried sticking a 'u' in front of my keyName when making the call, but it still returns none.
accessValueName = dictionaryName.get(u'keyName')
I also found several seemingly outdated methods to convert the entire dictionary to string values instead of unicode, however, they did not work, and I am not sure that I need the entire thing converted.
How can I either convert the entire dictionary from Unicode to String or just access the values using the keyname?
EDIT:
I just realized that I was trying to access a value from a nested dictionary that I did not notice was nested.
The solution is indeed:
accessValueName = dictionaryName.get('keyName')
Dictionaries store values in a hash table using the hash values of the object.
print(hash(u"example"))
print(hash("example"))
Yields the same result. Therefore the same dictionary value should be accessible with both.
I am looking for python equivalent to these data structure in C++
map<string,set<string>>
sorted by key
the value to be a set
and
map<key,val>
sorted by key
After reading this: https://docs.python.org/2/library/collections.html#collections.OrderedDict
I still didn't find anything suitable.
In python do you have 4 data structures: lists, tuples, sets and dicts.
You can create your own structure combining them:
First:
data = {'my_set':set()}
Second:
data = {'key': 'value'}
And you can sort this data structures using the collections module.
How can I sort a dictionary by key?
There is no perfect mapping between c++ and python; python is dynamically typed.
map<string,set<string>> is equivalent to (using OrderedDict to preserve the order of the keys, otherwise, dict suffice.):
OrderedDict(), where the keys are strings, and the values are sets in which you insert strings
from collections import OrderedDict
a = OrderedDict()
a['my_key'] = set()
a['my_key'].add('my_string')
note. The OrderedDict will not be ordered "by key", but by insertion
order of the keys (thanks to #timgeb in the comments)
writer = csv.DictWriter(result, fieldnames=Fnames)
for val in Fnames:
for row in List:
if str(row[1]) == str(val):
dic = {str(val): row[2]}
print dic.items()
writer.writerows(dic)
I'm getting:
Error: ValueError: dict contains fields not in fieldnames: S, c, h, o, o, l
I am writing the dictionary values to the CSV file but I am getting the following error. I have tried different methods but with no success. What I have to do to write rows to the CSV?
Fnames needs to be a list of field names to use. It looks like you have passed it the string "School" and it is iterating over each letter individually.
Check here for some documentation / examples.
Error message states that your dictionary contains keys that don't have a corresponding entry in your fieldnames parameter. Assuming that these are just extra fields, you can ignore them by using the extrasaction parameter during construction of your DictWriter object:
The specific error you're getting is because you're calling writer.writerows with a single dictionary as its argument. writerows expects to be given an iterable of dictionaries, not just one, and so it's misinterpreting things. It iterates over the dictionary (getting the keys) but expecting to be getting the inner dicts. When it iterates over those (to make sure the dictionaries have the expected keys), it is seeing the letters of the dictionary's key.
I'm not really sure what your logic is supposed to be though. Probably you shouldn't be iterating over Fnames at the top level, since every dictionary you write out needs to have every field in it (unless you specify a non-default value for the extrasaction parameter of DictWriter). Perhaps loop first over the List items, then over the Fname fields afterwards, adding a new key and value to the dictionary each time?
I have a dict, ast that is stored as:
{u'databaseConnections': {u'shard1': {u'username': u'user'}}}
I want to convert this into JSON so I can do something like:
user = dbConf['databaseConnections']['shard1']['username']
I've tried using json.dumps(ast, ensure_ascii=False), but this just gives me the error:
print dbConf['databaseConnections']['shard1']['username']
TypeError: string indices must be integers
What am I doing wrong?
Converting this thing to JSON is unnecessary and counterproductive; you can just do
user = ast['databaseConnections']['shard1']['username']
with your ast dict directly. dicts are key-value mappings; JSON is text. You're trying to access your data as a key-value mapping, not serialize it and send it over the internet.