Iterating over dictionary by skipping the first key-value - python

I have defined a dictionary with a key and a dataframe, like this
data = {'Value':[0,1,2,3,4]}
kernel_df = pd.DataFrame(data, index=['M0','M1','M2','M3','M4'])
my_dict = {'dummy':kernel_df}
And my_dict is later filled with appropriate data. Next, I want to iterate over the dictionary starting from the second key, because the first (index 0) is dummy and I want to skip that. If I use
for key in my_dict:
Then the first key is also read. If I use
for i in {1..len(my_dict)}:
df = my_dict[i]
I receive the following error
for i in {1..len(my_dict)}:
AttributeError: 'float' object has no attribute 'len'
How can I fix that?

A dictionary doesn't have an inherent order(well okay, things changed in Python 3.7 where they now maintain the order of insertion.
However, you still can't index a dictionary like you would index a list.
(Okay you can get close to that kind of behavior if you really so wished, but I'll address that towards the end).
In your case, you can just iterate through the keys and skip the key if it's 'dummy' (or whatever you've defined it as).
for key in my_dict:
if key != 'dummy':
do your thing
Perhaps a better alternative would be to simply remove the 'dummy' key once you know your dictionary has bee populated with proper values.
Now, coming back to getting the 'first key' because one is a >= Python 3.7 user:
Okay if someone really wanted to rely on the technical implementation of a version specific feature, they could probably do something like this:
for idx, key in enumerate(my_dict.keys()):
if idx != 0:
do your thing
This is far from idiomatic code though, so really, you shouldn't.

Related

Dictionary that doesn't exist returning name of string, how to skip this Python

I have a dictionary that holds different value and id's.
The first index in the dictionary does not hold the 'id' dictionary, but the second index does
The problem I am having is when I print:
return[0]['values']['id']
It returns
'id'
Because there is no such dictionary in the first index
The second index
return[1]['values']['id']
The 'id' dictionary does exist so returns
[{"id": "4651234", "type":"instant"}]
I'm trying to create a list of only the id values that exist, how do I get it to skip the all the indexes where the 'id' dictionary does not exist? Rather than stop the program and print the string 'id'.
You can just loop and use a if statement to check if the id exists or not :
id_list = []
for key in return:
if return[key]['values']['id'] != 'id':
id_list.append(return[key]['values']['id'])
(Btw you should avoid naming your variables with name like return or any other keyword that can have a signification for the language)
you can if the returned value it is a list or a string
if isinstance(return[0]['values']['id'],list):
#process the data
elif isinstance(return[0]['values']['id'],str):
#do nothing
Having said that, a couple of recommendations: I assume that you wrote it as an example but, just in case, is not possible to have "return" as the name of the variable since it is a reserved word.
Another point is that if the same call returns different things (i.e. the first returns a str, the second a list with a dictionary in it, etc), it may be an indication that the data needs some cleaning before trying to access it. Otherwise you may end up with nasty results and you won't know where they are coming from.

How can I access to a dictionary element indexed with a string?

I want to access to an element of a dictionary with a string.
For example, I have a dictionary like this:
data = {"masks": {"id": "valore"}}
I have one string campo="masks,id" I want to split this string with this campo.split(','). I obtain ['masks', 'id'] and with this I want to access to the element data["masks"]["id"].
This dictionary is an example, my dictionaries have more complexity. The point is that I want to access to the element data["masks"]["id"] with an input string "masks,id", or to the element data["masks"] with the string "masks" and to the element data["masks"]["id"]["X"] with the input string "masks,id,X" and so on.
How can I do this?
However, I won't recommend you to use the following method, as python dict is not meant to be accessed the way you want it to be, but since in Python you can change the object type at your own risk, I would like to attach the snippet which would get the work done for you.
So what I do is iterate over the keys and at each iteration fetch the child dictionary is present else put empty dictionary, the .get() method used, returns empty dict if the key was not found.
data = {"masks": {"id": "valore"}}
text = "masks, id"
nested_keys = text.split(", ")
nested_dict = data
for key in nested_keys:
nested_dict = nested_dict.get(key, {})
if (isinstance(nested_dict, str)):
print nested_dict
The point is that you are coming up with requirements that do not match the capability of the python-built-in dictionaries.
If you want to have nested maps that do this kind of automated "splitting" of a single key string like "masks, id, X" then ... you will have to implement that yourself.
In other words: the answer is - the built-in dictionary can't do that for you.
So, the "real" thing to do here: step back and carefully look into your requirements to understand exactly what you want to do; and why you want to do that. And going from there look for the best design to support that.
From an implementation side, I think what you "need" would roughly look like:
check if the provided "key" matches "key1,key2,key3"
if so, split that key into its sub-keys
then check if the "out dictionary" has a value for key1
then check, if the value for key1 is a dictionary
then check if that "inner" dictionary has a value for key2
...
and so on.

Python - If value in dictionary then

Here's my code
if "value" not in dictionary():
do something
else:
do something else
I get the error 'TypeError: 'dict' object is not callable.
I've tried changing the first line to
if dictionary["value"]:
But get a different error. Where am I going wrong here?
Assuming dictionary is in fact a dict() composed of key-values then it would be
if 'value' not in dictionary:
...etc
The error is essentially telling you that you are erroneously attempting to call a non-callable object as if it were a method/function.
If you are not particularly interested in whether or not a value exists you may use a method I am personally a fan of:
some_value = dictionary.get('value', 'valueIfNotPresent')
do_something(some_value)
The above allows you to provide a sentinel value (which is provided when the key does not exist). This can help with branch elimination (e.g. not having to if/else it, just allowing your code to act upon the sentinel) or at least reduce logic in checking for the existence of a key (unless the absence of a key is important).
Both are quite readable however and your mileage may vary.
EDIT:
#user1857805 is correct, if you are attempting to find out if a value is in a dictionary then the above (while still good and valid to know) is not enough. You will need to get the .values() as a list from the dictionary; however, as a dictionary may contain dictionaries you will need to recurse the dictionary to find all of the possibly stored values.
try using the following:
if 'value' not in dictionary.values():
do something
else:
do something else.

Efficiently iterating a dictionary in Python

So here's the problem, I'm importing a dictionary with anywhere from 6000 to 12000 keys. Then using a nested for algorithm to group them into a list inside of another dictionary. I'm using the following code to check if the key is in the dictionary:
for key in range(sizeOfOriginalKeys):
if key in key_data:
As you might imagine, this is taking forever since the sorting algorithm is fairly complex. I would like to only iterate through the keys in 'key_data', without doing 1000 to 11999 checks if there is that key in the dictionary. Is there a way to make a list of current keys? Then iterate through them? Or at least something more efficient than what I'm currently doing?
Current Code after Kevin's suggestion:
for key in key_data:
currentKey = key_data[key].name
if key_data[currentKey].prefList[currentPref] == currentGroup
key_data[currentKey].currentScore = getDotProduct()
group_data[currentGroup].keyList.append(key_data[currentKey])
group_data[currentGroup].sortKeys()
del key_data[currentKey]
The key names are integers.
At the end of the sorting algorithm I delete the key, if its been sorted into a group.
Now I get an error: dictionary changed size during iteration.
Thoughts?
You're trying too hard:
for key in key_data:
You can try
for key,value in key_data.items() :
print key
print value
you can access to value without calling key_data[key]

Remove certain keys from a dictionary in python

I'm trying to construct a dictionary that contains a series of sets:
{Field1:{Value1, Value2, Value3}, Field2{Value4}}
The trouble is, I then wish to delete any fields from the dictionary that only have one value in the set. I have been writing code like this:
for field in FieldSet:
if len(FieldSet[field]) == 1:
del(FieldSet[field])
But receive the error "RuntimeError: dictionary changed size during execution". (Not surprising, since that's what I'm doing.) It's not the be-all and end-all if I have to knock together some sort of workaround, but is it possible to do this?
Iterate over the return value from .keys() instead. Since you get a list of keys back, it won't be affected by changing the dictionary after you've called it.
A sometimes-preferable alternative to changing FieldSet in place is sometimes (depending on the amount of alterations performed) to build a new one and bind it to the existing name:
FieldSet = dict((k, v) for k, v in FieldSet.iteritems()
if len(v) != 1)
There is the pop method. It removes the element that a key calls. With respect to your example this looks like:
for field in FieldSet.keys():
if len(FieldSet[field]) == 1:
FieldSet.pop(field)
This is in python 3.2, but I'm not sure if it's a new feature:
http://docs.python.org/dev/library/stdtypes.html#dict.pop
Just tried it and it works as advertised.

Categories

Resources