I want to get the first value from a sequence for a key within a dictionary object.
This is the dictionary object:
{0: (mdb.models['EXP-100'].parts['hatpart-100'].vertices[1],
(62.5242172081597, 101.192447407436, 325.0))}
The Key is 0, and I'd like to get the first value in the sequence of values
(vertex object and coordinates), specifically the vertex object.
When you're trying to get a specific item from a dictionary containing a list you can do it by indicating the key and then index that you're looking for. So:
your dictionary ={'key':[1,2,3]}
result = your_dictionary['key'][0]
where key is the first item you want and if it contains a list, then the "0" is asking for the first item of the list.
The above will return the value "1".
You can iterate over this to get all values and you can add as many [] as you need to get to the specific value you need.
That being said, your data doesn't look quite right. The dictionary should contain "key":"object" sets. Those objects can be further dictionaries themselves or lists, but what you've provided seems to be off. You may have to manipulate the data to fit what you need it to do before your can perform any operations on it. This could help with that first: "Deparsing" a list using pyparsing
Related
I'm hitting my head on something that should be simple.
I have a query like this:
MyModel.objects.filter(...).aggregate(max_value=Max('value'))
and this does, indeed, return a (dictionary) with key 'max_value' and value that maximum value.
But what I want is the object that has that maximum value. Or, at least, some subset of the fields of that object, but the max value is just the selector
You can work with the .latest(…) [Django-doc] to obtain the object with the maximum of certain field(s). This will internally order the queryset and then obtain the last object, so:
MyModel.objects.filter(…).latest('value')
I have a list of dictionaries
[{'cat': array([-3.01740319e-02, 4.39191431e-01, 3.24975878e-01,
-2.81387717e-02,...]},{},{},{}], where each dictionary is of a different length.
Some of the keys in the dictionaries are the same and I would like to check if their corresponding values are unique or the same.
I have used .update to merge all dictionaries and then check, but then realised that this would overwrite some values and not show me if there are any different/same values.
final = {}
for d in temp_dict_array:
final.update(d)
All I would need is a method of showing me that two keys in different dictionaries have either the same or different value, even just through a simple print statement.
Find the keys that are in both dictionaries, then check the values that correspond to those keys.
Where d1 and d2 are 2 dictionaries you want to check.
matching_keys = [key for key in d1.keys() if key in d2]
for key in matching keys:
if d1[key] == d2[key]:
# They're the same
else:
# They're not the same
(untested code)
if dict1[key] == dict2[key]:
...
I'm having some trouble extracting info from a Python object. Basically, using notation like this works to get down to values within a dict I am working with:
clean_content['Al38zGKg6YC4']['image']
I was expecting to see another nested dict which contained the key/value that I wanted to extract. However, what's there is a list that looks like a dict[1]
I'm looking to extract the 'permalink' field from this list, and then tie it back to the page ID in the original dict. Any suggestions?
I came to a working solution as follows: converting the original dictionary into a pandas dataframe, I extracted the column containing the lists of image data. Each of these lists contained URLs for multiple images, so I extracted the one required using dicts:
image_df_temp = {}
image_df_url = {}
for i in range(len(image_df_base.index)):
image_df_temp[i] = pd.DataFrame(image_df_base.image[i])
image_df_url[i] = image_df_temp[i].iloc[0]
Finally, I edited the dicts missing the required metadata using .get:
for i in range(len(image_df_base.index)):
image_df_url[i] = image_df_url[i].get('permalink', "No image available")
What I have:
A CSV which I populated with rows of text, which are one word per cell.
Micro level: Attempting:
I am trying to create a dictionary where each row is a Key and each Key is assigned an empty list as a variable (see below).
I can do this one row at a time by converting the list to a tuple -->
creating an empty list -->
Adding the tuple to my dictionary as a key and assigning the empty list as the variable
However, I would like to do this in an automatic fashion as doing this individually is tedious.
Macro level: Attempting:
I want to assign a list of keywords (tags) to each row in my CSV to call upon the text later based on their tags.
My question:
Is there a way to do this the way I am describing?
Am I going about it wrong and should be doing this a different way?
*edit: I am thinking that if I flip this I could solve my overall issue.
For example make x amount of tags as key values for my tag dictionary and make a one time run through to assign each key with a empty dictionary value. Then populate the dictionaries with the text from my CSV.
This would not remove the one by one method; however, would reduce the amount of times I would need to enter Key/Value pairs as I am more likely to have more text than tags.
see code below
!#Python3
import csv
import os
import string
#open CSV and assign var to the list content
outputFile = open("output.csv", encoding="utf-8")
outputReader = csv.reader(outputFile)
data = list(outputReader)
#Get rid of empty cells
for list in data:
for object in list:
while "" in list:
list.remove("")
#open a dictionary
tags = {}
#Turn first row of CSV into a tuple
article1 = tuple(data[1])
#generate empty list
article1_tags = []
#Assign empty list as a variable to the article1 Key and put in tags dictionary
While True:
if article1 in tags :
break
else:
tags[article1] = article1_tags
Now that I have bit more of idea of what you are trying to acheive I would suggest using a list of dictionary's. Each dictionary containing the data about each article (or row from your csv file). The key here is that a csv file is still a plain text file, there is nothing special about csv. In fact I would avoid using excel altogether and edit using a text editor.
I would start by opening the file and reading each row (line) from the file into a key/value pair of a dictionary.
The cool thing about python 3 is that you do that very easily without extra modules.
csvfile = open('output.csv', encoding='utf-8')
articlelist = []
for line in csvfile:
articlelist.append(dict(textkey=line,tagskey=[]))
Using the iterator 'line' in this context with a text file stream object will automatically go row by row and take all the text of that line as a single string. So line is a string object here.
Once you have list of dictionary's like this you can simply iterate through the articlelist printing out or adding tags or doing whatever you wish even adding more key/value pairs to each dictionary. Doing it in this way means that not all the dictionary's need to follow the same format (although thats desirable).
I added the tagskey key and the value is an empty list which you can add to later.
Do not use infinite while loops or while loops at all to go through lists etc. Always use the
for iterator in theList:
method.
I would also look into using the JSON format for your little exercise here. I think it will lend itself much nicer to what you are trying to acheive. And with Python JSON is very easily read and then output again all using plain text. You could then output to a JSON text file manually edit it and then python read it again and process it.
I hope this helps.
Simple question that I can't seem to find an answer to:
How do I add/append a key to a dictionary that resides in a list of dictionaries?
Given the list below:
list = [{'key-1': 'value-1', 'key-2': 'value-2'}, {'key-A': 'value-A'}]
I want to add 'key-B": "value-B' in the second dictionary for the result to be:
list = [{'key-1': 'value-1', 'key-2': 'value-2'},
{'key-A': 'value-A', 'key-B': 'value-B'}]
I thought I could just .update or .append to it but, no such luck.
Any assistance with this is greatly appreciated.
just do this.
list[1]['key-B'] = 'value-B'
OUTPUT
print(list)
[{'key-2': 'value-2', 'key-1': 'value-1'}, {'key-B': 'value-B', 'key-A': 'value-A'}]
Dictionary don't have any append method, For example if you have a dictionary as
dict = {'First':1, 'Second':2},
then you can add a third item as
dict['Third']=3.
Similarly in your case you want to change the second element of your list so list[1] will represent your second element and this element is dictionary so you can operate in the same way as dictionary
list[1]['key-B'] = 'value-B'
Your list has two elements and in this case both are dictionaries. Dictionary do have a update method and if you want to use update of dictionary then first access the dictionary element of your list and then update
list[1].update({'key-C':'value-C'})
You can check what methods are available using dir(list[1]) in your python interactive shell