Which index to use in order to access items in defaultdict - python

I am using var_dict = defaultdict(list).
Then the key is 'NODE' and value is a list.
I am able to iterate thru the values. But if I want to access elements ['1974'], ['993'],['198']... in this example can you please tell me what what would be the for loop construction for this.
var_dict['NODE']
[[['1013'], ['1974'], ['0/5']], [['1013'], ['993'], ['0/9']], [['9999'], ['198'], ['0/5']], [['9999'], ['992'], ['0/9']]]
I am able to iterate thru dictionary values given a key. My question is, what if I want to access items
for item in node_PS_if_list['IF_PSE2']:
for item1 in item:
will list the respective value. What I need is to access the second element like zz[0][1], zz[1][1], ZZ[2][1] etc.
I would need to increment a variable i and pass it like [i][0], [1][1], [2][1] etc. I would appreciate your assistance to address syntax for this.

var_dict = {'NODE':[[['1013'], ['1974'], ['0/5']], [['1013'], ['993'], ['0/9']], [['9999'], ['198'], ['0/5']], [['9999'], ['992'], ['0/9']]]}
r = [x[1] for x in var_dict['NODE']]
print(r)
Result:
[['1974'], ['993'], ['198'], ['992']]
If you want to iterate over these:
for element in [x[1] for x in var_dict['NODE']]:
# do your thing here

Related

How to index a list of dictionaries in python?

If I have a list of dictionaries in a python script, that I intend to later on dump in a JSON file as an array of objects, how can I index the keys of a specific dictionary within the list?
Example :
dict_list = [{"first_dict": "some_value"}, {"second_dict":"some_value"}, {"third_dict": "[element1,element2,element3]"}]
My intuitive solution was dict_list[-1][0] (to access the first key of the last dictionary in the list for example). This however gave me the following error:
IndexError: list index out of range
the key inputted into the dictionary will pick the some value in the format dict = {0:some_value}
to find a specific value:
list_dictionary = [{"dict1":'value1'},{"dict2","value2"}]
value1 = list_dictionary[0]["dict1"]
the 'key' is what you have to use to find a value from a dictionary
Example:
dictionary = {0:value}
dictionary[0]
in this case it will work
but to pick the elements we will do
values = []
for dictionary in dict_list:
for element in dictionary:
values.append(dictionary[element])
Output:
['some_value', 'some_value', ['element1', 'element2', 'element3']]
dict_list = [{"first_dict": "some_value"}, {"second_dict":"some_value"}, {"third_dict": ['element1','element2','element3']}]
If your dict look like this you can do as well
dict_list[-1]["third_dict"]
You can't access 'the first key' with a int since you have a dict
You can get the first key with .keys() and then
dict_list[-1].keys()[0]
By using dict_list[-1][0], you are trying to access a list with a list, which you do not have. You have a list with a dict key within a list.
Taking your example dict_list[-1][0]:
When you mention dict_list you are already "in the list".
The first index [-1] is referring to the last item of the list.
The second index would only be "usable" if the item mentioned in the previous index were a list. Hence the error.
Using:
dict_list=[{"first_dict": "some_value"}, {"second_dict":"some_value"},{"third_dict": [0,1,2]}]
to access the value of third_dict you need:
for value in list(dict_list[-1].values())[0]:
print(value)
Output:
0
1
2
If you know the order of dictionary keys and you are using one of the latest python versions (key stays in same order), so:
dict_list = [
{"first_dict": "some_value"}
, {"second_dict":"some_value"}
, {"third_dict": ["element1", "element2", "element3"]}
]
first_key = next(iter(dict_list[-1].keys()))
### OR: value
first_value = next(iter(dict_list[-1].values()))
### OR: both key and value
first_key, first_value = next(iter(dict_list[-1].items()))
print(first_key)
print(first_key, first_value)
print(first_value)
If you have the following list of dictionaries:
dict_list = [{"key1":"val1", "key2":"val2"}, {"key10":"val10"}]
Then to access the last dictionary you'd indeed use dict_list[-1] but this returns a dictionary with is indexed using its keys and not numbers: dict_list[0]["key1"]
To only use numbers, you'd need to get a list of the keys first: list(dict_list[-1]). The first element of this list list(dict_list[-1])[0] would then be the first key "key10"
You can then use indices to access the first key of the last dictionary:
dict_index = -1
key_index = 0
d = dict_list[dict_index]
keys = list(d)
val = d[keys[key_index]]
However you'd be using the dictionary as a list, so maybe a list of lists would be better suited than a list of dictionaries.

Trying to call the first element of a tuple by the value of the second element (within a loop)

The title is a bit confusing but I am essentially trying to store the name x of a tuple (x,y) by calling the values of y. The tuples are in a list, and there are three of them. However, this data may change so I want this loop to be able to process any sort of list length as long as the form comes in tuples. Additionally my tuples are in (str, [list]) form. Here is an example of my code.
key, val = list(d.keys()), list(d.values())
for i in val:
if i == group_ids[0]:
for x,y in list(d.items()):
if y == i:
print(x,y)
I have created a defaultdict previously in order to access my list of tuples in (str, [list]) format because ipywidgets8 no longer accepts dictionaries. After having successfully selected the list of values based on the str in the widgets interface I am looking to store the name of the selected list so that I can save each file based on their respective name. I know with pandas dataframe you can call the value of one column based on the value of another with .loc and I am trying to do something similar with my list of tuples but cannot figure out how. The group_ids variable is the list of selected values received from the ipywidgets button. I have to call [0] position because it has been stored with double brackets. Even more simply put, I want (this is not in any coding language just how my brain can best present this in human words):
FOR i IN val,
if i == group_ids[0]
PRINT x of key at the index where i in val is found
I hope this explanation is clear. I feel that this should not be so difficult to figure out but for some reason I cannot.
EDIT:
A sample of my data
group_ids = [[5876233, 5883627, 5891029, 5892881, 5896571, 5900242, 5902043, 5905766, 5905796, 5913064, 5913075, 5913080, 5914875, 5920356, 5924048, 5925824, 5927655, 5929456, 5929479, 5931307, 5934950, 5936704, 5940344, 5943972, 5944002, 5945785, 5947627, 5951172, 5951181, 5954751, 5958339, 5958354, 5958358, 5965416, 5965424, 5967145, 5968843, 5972099, 5978640, 5981887, 5983501, 5993193, 5967178, 5967171, 5963649, 5951209, 5929476, 5958331, 5938533, 5933134, 5918577, 5958359]]
list(d.items()) = [('Libraries', [5876233, 5883627, 5891029, 5892881, 5896571, 5900242, 5902043, 5905766, 5905796, 5913064, 5913075, 5913080, 5914875, 5920356, 5924048, 5925824, 5927655, 5929456, 5929479, 5931307, 5934950, 5936704, 5940344, 5943972, 5944002, 5945785, 5947627, 5951172, 5951181, 5954751, 5958339, 5958354, 5958358, 5965416, 5965424, 5967145, 5968843, 5972099, 5978640, 5981887, 5983501, 5993193, 5967178, 5967171, 5963649, 5951209, 5929476, 5958331, 5938533, 5933134, 5918577, 5958359]), ('Sport Facilities', [5812360, 5817970, 5818061, 5821851, 5823750, 5823751, 5827499, 5829344, 5829423, 5831312, 5833208, 5838752, 5840647, 5842526, 5842539, 5842575, 5842583, 5844396....)]
d.keys = dict_keys(['Libraries', 'Sports Facilities', 'Youth Facilities'])
I want the respective key for the list of ids seen in the group_ids variable
So I think you just need:
for k, v in d.items():
if v[0] == group_ids[0]:
print(k, v)
Checking if v == group_ids would be more precise, but I assume that all ids are different.

How to read and print a list in a specific order/format based on the content in the list for python?

New to python and for this example list
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
There are 3 categories of name, job, and gender. I would want those 3 categories to be on the same line which would look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
My actual list is really big with 10 categories I would want to be on the same line. I am also trying to figure out a way where if one of the categories is not in the list, it would print something like N/A to indicate that it is not in the list
for example I would want it to look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
<name>susan</name>, <job>teacher</job>, <gender>female</gender>
<name>john</name>, N/A, <gender>male</gender>
What would be the best way to do this?
This is one way to do it. This would handle any length list, and guarantee grouping no matter how long the lists are as long as they are in the correct order.
Updated to convert to dict, so you can test for key existence.
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
newlst = []
tmplist = {}
for item in lst:
value = item.split('>')[1].split('<')[0]
key = item.split('<')[1].split('>')[0]
if '<name>' in item:
if tmplist:
newlst.append(tmplist)
tmplist = {}
tmplist[key] = value
#handle the remaining items left over in the list
if tmplist:
newlst.append(tmplist)
print(newlst)
#test for existance
for each in newlst:
print(each.get('job', 'N/A'))

How to access a dict's values and delete them?

I have a Python dict stuffs with keys and values(list);
{'car':['bmw','porsche','benz'] 'fruits':['banana','apple']}
And I would like delete first value from cars: bmw and first value from fruits: banana
How can I access and delete them please? I have tried .pop(index), but it doesn't work...
You can create a new dictionary where you skip the first element using [1:]
stuffs = {'car':['bmw','porsche','benz'], 'fruits':['banana','apple']}
stuffs_new = {k:v[1:] for k,v in stuffs.items()}
# {'car': ['porsche', 'benz'], 'fruits': ['apple']}
An easy way of doing this is to use a for loop and iterate over each item in you're dictionary, and pop the first element:
dictionary = {'car':['bmw','porsche','benz'], 'fruits':['banana','apple']}
for key in dictionary:
dictionary[key].pop(0)
Or, as a list comprehension
dictionary = {'car':['bmw','porsche','benz'], 'fruits':['banana','apple']}
[dictionary[i].pop(0) for i in dictionary]
These pieces of code reference the dictionary at each of it's keys ('car' and 'fruits') and then proceeds to use pop on the values indexed by these keys.
Edit:
Don't use a list comprehension if you don't intend to store the list. In the case where you are iterating over large values, you could run into memory errors due to storing a whole load of useless values. Such as in this case:
[print(i) for i in range(9823498)]
This will store 9823498 None values*, where as a for loop would not. but still achieve the same thing.
You were almost there.
Use either:
del dict[key]
Or
dict.pop(key, value)
The second will remove but also leave the item available as a return

How can I associate a dict key to an attribute of an object within a list?

class SpreadsheetRow(object):
def __init__(self,Account1):
self.Account1=Account1
self.Account2=0
I have a while loop that fills a list of objects ,and another loop that fills a dictionary associating Var1:Account2. But, I need to get that dictionary's value into each object, if the key matches the object's Account1.
So basically, I have:
listofSpreadsheetRowObjects=[SpreadsheetRow1, SpreadsheetRow2, SpreadsheetRow3]
dict_var1_to_account2={1234:888, 1991:646, 90802:5443}
I've tried this:
for k, v in dict_var1_to_account2.iteritems():
if k in listOfSpreadsheetRowObjects:
if self.account1=k:
self.account2=v
But, it's not working, and I suspect it's my first "if" statement, because listOfSpreadsheetRowObjects is just a list of those objects. How would I access account1 of each object, so I can match them as needed?
Eventually, I should have three objects with the following information:
SpreadsheetRow
self.Account1=Account1
self.Account2=(v from my dictionary, if account1 matches the key in my dictionary)
You can use a generator expression within any() to check if any account1 attribute of those objects is equal with k:
if any(k == item.account1 for item in listOfSpreadsheetRows):
You can try to use the next function like this:
next(i for i in listOfSpreadsheetRows if k == i.account1)
If you have a dictionary d and want to get the value associated to the key x then you look up that value like this:
v = d[x]
So if your dictionary is called dict_of_account1_to_account2 and the key is self.Account1 and you want to set that value to self.Account2 then you would do:
self.Account2 = dict_of_account1_to_account2[self.Account1]
The whole point of using a dictionary is that you don't have to iterate through the entire thing to look things up.
Otherwise if you are doing this initialization of .Account2 after creating all the SpreadsheetRow objects then using self doesn't make sense, you would need to iterate through each SpreadsheetRow item and do the assignment for each one, something like this:
for row in listofSpreadsheetRowObjects:
for k, v in dict_of_account1_to_account2.iteritems():
if row.Account1 == k:
row.Account2 = v
But again, you don't have to iterate over the dictionary to make the assignment, just look up row.Account1 from the dict:
for row in listofSpreadsheetRowObjects:
row.Account2 = dict_of_account1_to_account2[row.Account1]

Categories