I have a array of hashes like:
detail = [{'name': 'Adam'}, {'name': 'Jackie'}]
Now what I want to do is create a new dict like:
{'name' : 'Sandra'}
What I did was:
for i in detail:
for key_in_i in i:
dict(key_in_i = 'Sandra')
What I would like to get is {'Name': 'Sandra'}. But if I do this I am getting {'key_in_u': 'Sandra'} because I have set the key as key_in_i. I don't know how to access the value of key from for loop to the new dict. If it was in Ruby I would have done #{key_in_i} and it would have given me the required value. I also tried new_dict = dict("%s" %key = i[key]) but it gives me error key cannot be the expression. I would be thankful if anyone could help me solve this issue!
The easiest solution in this particular case is
for i in detail:
print dict.fromkeys(i, "Sandra")
You could also use a dictionary literal:
for i in detail:
for key_in_i in i:
{key_in_i: "Sandra"}
(Not sure what you are actually trying to achieve since your example code is effectively doing nothing.)
Related
I have a list of dicts that are JSON objects, like this:
[{'addressId': 12345, 'city': 'London', 'country': 'UK'}, {'addressId': 67890, 'city': 'Berlin'}
For some of the entries there are some JSON keys missing (not just the values) - in the example above the second address is missing the country. This causes problems down the line when I want to write this data to MySQL.
So I think what I want to do is add the missing keys with empty values. I'm wondering (a) if this is the right approach, and (b) how I would go about doing that.
FWIW, we're talking about a few million rows.
Any hints are greatly appreciated.
Whether or not this is the correct approach depends on the use case down the line. You could simply loop through each element in the list, and, if the key doesn't exist, add it with a default value:
for obj in arr:
if key1 not in obj:
obj[key1] = # default value
# and continue for other keys
I would recommend just doing dictionary.get() for each key at the point of putting the info into the database, that way you can add a default value there if it's missing.
objects = [{'addressId': 12345, 'city': 'London', 'country': 'UK'}, {'addressId': 67890, 'city': 'Berlin'}]
for object in objects:
country = object.get('country', None)
city = object.get('city', None)
The default return value for .get() if it doesn't find the key, is None. But I included it in there to show you can put anything there.
If data is not uniform or difficult to present in tabular format than mongodb is the better option.
if strict to MYSQL than
As Tob suggested ,make the default values .
I have the following dictionary:
watch_list= {'videos': [{'systemId': 'qre', 'duration': 19}, {'systemId': 'abc', 'duration': 19}]}
now I wanted to check if the systemId already exists in the dictionary and if yes then update duration by systemId.
hence I am trying the following code:
def update_duration(watch_list,system_id,duration):
watch_history= next((a for a in watch_list if a['systemId'] == system_id), None)
if watch_history:
watch_history['duration'] =duration
return watch_history
but this gives me an error:
*** TypeError: string indices must be integers
I am new to python, I have read stack overflow other solutions but couldnt made it work. can anyone help me a little here, on how to update the value by the systemId?
I am using python 3 and flask
When you iterate through a dictionary with something like
my_dictionary = { 'hello' : ['I', 'am', 'a', 'dictionary'] }
for entry in my_dictionary:
print entry
The output will be hello, as it iterates through its keys by default. As it appears you're actually wanting to iterate through the dictionary's values, you'll want to call the values() function, or itervalues() in Python2.
Beyond that, you're then running into an issue with your generator comprehension's if statement. At that point, your a variable is holding a list of dictionaries---what used to be the value found by watch_list['videos'].
I have a list of dicts ('sortings') that I am trying to iterate through to access a values in one specific key of each dict. My code keeps saying that there is a key error for the desired value in the dict. If I print inside the for loop, it prints with the values entered but once I exit the for loop it says there is a key error.
for i in range(sort_len):
sentence = sortings[i]['content']
containing_messages.append(sentence)
print(containing_messages)
This is an answer for my understanding of the question. I would require the given input and expected output to provide a better answer.
list_of_dicts = [{'keya':'value1_1','keyb':'value2_1','keyc':'value3_1'},
{'keya':'value1_2','keyb':'value2_2','keyc':'value3_2'},
{'keya':'value1_3','keyb':'value2_3','keyc':'value3_3'}]
list_of_key_values = [my_dict['keyb'] for my_dict in list_of_dicts]
print list_of_key_values
The goal: from the string below I need to extract, side by side, the 'key' value and the 'query' value, which are returned by an API.
I'm not a Python expert, but to me it seems that the API that I'm hitting returns a dictionary inside a list, which themselves are inside a dictionary.
That seems to be the crux of the issue [the involvement of the list]. Note, the API may return multiple lines such as the one below.
{'Condition1': 'True', 'Load': 'Normal', 'query': 'xyz', 'results': [{'F1': 'abc', 'F2': 'def','Key': 'dfg4325'}]}
from the example above, I'm trying to retrieve a combined string that would be i.e. like a CSV as follows:
'xyz','dfg4325'
I've tried a number of tactics but nothing is working. The 'key' field inside the list's dictionary is always alpha-numeric - otherwise I'd have a hack for it.
Any thoughts would be appreciated. I googled this and just can't hit the right answer.
You can iterate a dict and a list to find the value of 'key', for example,
for key, val in response.items():
if isinstance(val, list):
for dic in val:
if 'Key' in dic:
val_of_key = dic.get('Key')
break
if isinstance(search_response["results"], list):
for dic in search_response["results"]:
if "Key" in dic:
val_of_key = dic["Key"]
decoded_Key = (val_of_key + "|" + search_response["query"]+ "\n")
# setup a dummy text file in the same fldr as the pycharm project
# appends the results to a text
with open("dummy.txt", "a") as query_file:
query_file.write(decoded_Key)
I have a large python dict created from json data and am creating a smaller dict from the large one. Some elements of the large dictionary have a key called 'details' and some elements don't. What I want to do is check if the key exists in each entry in the large dictionary and if not, append the key 'details' with the value 'No details available' to the new dictionary. I am putting some sample code below just as a demonstration. The LargeDict is much larger with many keys in my code, but I'm keeping it simple for clarity.
LargeDict = {'results':
[{'name':'john','age':'23','datestart':'12/07/08','department':'Finance','details':'Good Employee'},
{'name':'barry','age':'26','datestart':'25/08/10','department':'HR','details':'Also does payroll'},
{'name':'sarah','age':'32','datestart':'13/05/05','department':'Sales','details':'Due for promotion'},
{'name':'lisa','age':'21','datestart':'02/05/12','department':'Finance'}]}
This is how I am getting the data for the SmallDict:
SmallDict = {d['name']:{'department':d['department'],'details':d['details']} for d in LargeDict['results']}
I get a key error however when one of the large dict entries has no details. Am I right in saying I need to use the DefaultDict module or is there an easier way?
You don't need a collections.defaultdict. You can use the setdefault method of dictionary objects.
d = {}
bar = d.setdefault('foo','bar') #returns 'bar'
print bar # bar
print d #{'foo': 'bar'}
As others have noted, if you don't want to add the key to the dictionary, you can use the get method.
here's an old reference that I often find myself looking at.
You could use collections.defaultdict if you want to create an entry in your dict automatically. However, if you don't, and just want "Not available" (or whatever), then you can just assign to the dict as d[key] = v and use d.get(k, 'Not available') for a default value
Use the get(key, defaultVar) method to supply a default value when the 'details' key is missing:
SmallDict = {d['name']:{'department':d['department'],'details':d.get('details','No details available')} for d in LargeDict['results']}