Key error in dictionary - python - python

I have two dictionaries:
One is :
data_obt={'Sim_1':{'sig1':[1,2,3],'sig2':[4,5,6]},'Sim_2':{'sig3':[7,8,9],'sig4':[10,11,12]},'Com_1':{'sig5':[13,14,15],'sig6':[16,17,18]},'Com_2':{'sig7':[19,20,21],'sig9':[128,23,24]}}
Other one is:
simdict={'sig1':'Bit 1','sig2':'Bit 2','sig3':'Bit 3','sig4':'Bit 4','sig5':'Bit 5','sig6':'Bit 6','sig7':'Bit 7','sig9':''}
Now I have to do return_data[fpath].append(data_obt[key][item]), where fpath = 'sig9',key='Com_2' and item = 'sig9'
But when I tried to execute this it is throwing error like : KeyError: 'sig9'
My expected return_data is {'sig9':[128,23,24]}
Can anyone please help me out?

As I understand, return_data is another dict. If so, it doesn't (as of yet) have a key named fpath (which is 'sig9'). Hence, the error.
To avoid it, you should either use defaultdict, or initialize this element as an empty list every time you come across a new key.

Related

iterate threw list and if value doesnt excist hide error and continue

I've got a List like:
results = ['SDV_GAMMA','SDV_BETA,'...','...']
and then comes and for loop like:
for i in range (len(results)):
a = instance.elementSets[results[i]]
The strings defined in the result-list are part of a *.odb result file and if they didn't exist there comes an error.
I would like that my program doesn't stop cause of an error. It should go on and check if values of the others result values exist.
So i do not have to sort every result before i start my program. If it´s not in the list, there is no problem, and if it exists i get my data.
I hope u know what i mean.
You can use try..except block
Ex:
for i in results
try:
a = instance.elementSets[results[i]]
except:
pass
You can simply check the presence of results[i] in instance.elementSets before extracting it.
If instance.elementSets is a dictionary, use the dict.get command.
https://docs.python.org/3/library/stdtypes.html#dict.get

how to access values in a dictionary in python without knowing the actual values?

I am a python rookie and so my question is simple (yet I couldn't find the answer here):
I need to access values in my dictionary (named 'database') but without knowing the actual values. So lets say I want to print the first value of the dictionary whatever it is. I found this:
print(database.values()[0].keys()[0])
Which seems to be what I'm looking for but when running the script I get this error:
TypeError: 'database' object does not support indexing
Can you please help?
You might want to check out Ordered Dict:
As others mentioned in the comments, you would get the elements in no particular order because dictionaries are unordered.
This sample code works:
from collections import OrderedDict
database = OrderedDict()
database = {
"key1": {"key10": "value10", "key11": "value11"},
"key2": {"key20": "value20", "key21": "value21"}
}
If you want to print out or access all first dictionary keys in database.values() list, you may use something like this:
for key, value in database.items():
print value.keys()[0]
If you want to just access first key of the first item in database.values(), this may be useful:
print database.values()[0].keys()[0]
Hope this helps.

Python dictionary append

I have trouble making my code work. I post only relevant part of the code.
File im using is in this page https://programmeerimine.cs.ut.ee/_downloads/lapsed.txt
First number is parent and 2nd his child. I also had different filed which translated numbers into name. (I made list ID_name it works fine i checked)
This other part of the code works fine except when I'm trying to add value to existing key.I get error AttributeError: 'str' object has no attribute 'append'
for line in f:
part=line.split(" ")
parent=part[0]
kid=part[1].strip()
for el in ID_name:
if parent == el[0]:
parent=el[1]
if kid == el[0]:
kid=el[1]
if parent not in parents.keys():
parents[parent]=kid
else:
parents[parent].append(kid)
The append function you're referencing only works for lists: https://docs.python.org/2/tutorial/datastructures.html
If you want to add a new key/value pair to a dictionary, use: dictionary['key'] = value .
You can also opt for: dictionary.update({'key': value}), which works well for adding multiple key/value pairs at once.
You need to initialize a list rather than just adding the object. Change this:
parents[parent]=kid
to this:
parents[parent] = [kid]
This will give you a list to which you can append() new objects, rather than just a string.

Can't delete keys from HASH in Redis

I have created a hash in redis database and i have put some keys and their values in it. I want now to delete everything that is in the hash.I am using hdel but i cannot make it work. I am confused on what should be in hdel(...) and the documentation doen't help me.Right now i have the following:
test_hash = redis_cache.hgetall(hash_name)
for key,value in test_hash.items():
i = redis_cache.hdel(hash_name,*key)
in hdel.() i have tried many different things but nothing seems to work.After the code "deletes" everything in the hash, i can still do redis_cache.hgetall() and get the same keys and values.
Anyone that knows something more? I am using Python.
Ok , i found what i was doing wrong. I have to create a list of keys and do the following :
list = []
for key,value in test_hash.items():
list.append(key)
i = redis_cache.hdel(hash_name,*list)

How to Access a List through a key?

I have a program that has a save file full of lists. It Loads up the Items by making lists. It gets the Names from the file too. Since I couldn't "unstring" a string so I put the names as keys. My problem is re-saving the lists when you are done using the program. I cant seem to access the contents inside the list to write them to a file. I have another List with keys so I can access the Names.
ListKey = {1:'Food', 2:'Veggie'}
List={'Food':['apple','pear','grape'], 'Veggies':['carrot','Spinach','Potato']}
file.write(ListKey[1]) #works fine
currentList=ListKey[1]
file.write(List[currentList[1]]) #Doesn't Work
When I try to do the code above, I get a Key Error, I know it is trying to write the 'o' in food. Is there anyway to get around this?
It looks like you are trying to access a value inside your key pairs. Try:
List[currentList][0] to access 'apple'
List[currentList][1] to access 'pear'
etc...
alternatively if you want all the values, it would look like
List[currentList] or
List['Food']
Hope this helps, just your syntax of how to access the list inside.
edit:
https://docs.python.org/2/tutorial/datastructures.html#nested-list-comprehensions
(added link to data structure docs)
currentList[1] is just the value o, use:
file.write(List[currentList])
ListKey = {1:'Food', 2:'Veggie'}
List={'Food':['apple','pear','grape'], 'Veggies': ['carrot','Spinach','Potato']}
currentList = ListKey[1] #'Food'
currentList[1] # 'o'
You are actually indexing into the string "Food". Hence currentList[1] is 'o'. Since List has no key 'o' you get at key error.

Categories