i'm trying to append to a dictionary. there are two loops. the name of the keys depends on the value of the inner loop and the key is the value of a variable which is updated within the loop. my script is
def append_value(dict_obj, key, value):
# Check if key exist in dict or not
if key in dict_obj:
# Key exist in dict.
# Check if type of value of key is list or not
if not isinstance(dict_obj[key], list):
# If type is not list then make it list
dict_obj[key] = [dict_obj[key]]
# Append the value in list
dict_obj[key].append(value)
else:
# As key is not in dict,
# so, add key-value pair
dict_obj[key] = value
for x in range(tot):
dict=['output'=x]
for a in range(33,91):
index_val=(a*sum_t)/x
# now i'm trying to create key names that would be year_33 year_34 and so on
head=''
head='year_{}'.format(a)
append_value(dict, head=avg_PMI)
i get the error name 'append_value' is not defined. would appreciate any help. i would like to loop over values of tot and the (33,91) range. each combination of the two gives a unique values and i want to create a dictionary which will become a csv where x values are rows, a is the column.
thanks!
edited: to show append_value function
The cause of the error is that when you call a function with head=avg_PMI, python assumes that head is an argument. For append_value, the only arguments are dict_obj, key and value. I assume that you want to add a value to the dictionary such that head=avg_PMI. To do this, you have to call the function append_value in the following way:
append_value(dict, head, avg_PMI).
Related
So I got this dictionary from a csv file and I would like to look for a specific key inside this dictionary (actually the og idea was to search for said key in the csv file and then make a dictionary from that key down) but I don't really know how to do it.
So far I got:
df = pd.read_csv('data.csv')
dict = df.to_dict(orient='dict')
for index, line in enumerate(dict):
if "Wavelength [nm]" in line:
print(index)
The idea is to know the index of "Wavelength".
If you want the value of a key without knowing whether it's in the dict, often the most natural way is
value = dict.get( key, defaultvalue)
defaultvalue is what you would set value to in your code once you had established that the key is not present. Often, None, or an empty list or tuple.
If you just waht to check whether the key is present without accessing the value, use
if key in dict:
# do stuff
you can use:
if key in dict:
print(key,dict[key])
I have a dictionary which looks as shown below. Now I need to get the key its corresponding path together so as to use it further to identify its slot number based on the key. How can I achieve that?
I tried an approach but it is giving me key error.
What you need can easily be implemented as:
>>> {key: value["mpath"] for key, value in multipath.items()}
{'/dev/sdh': '/dev/mapper/mpathk', '/dev/sdi': '/dev/mapper/mpathk',
'/dev/sdg': '/dev/mapper/mpathj', '/dev/sdf': '/dev/mapper/mpathj',
'/dev/sdd': '/dev/mapper/mpathi', '/dev/sde': '/dev/mapper/mpathi',
'/dev/sdb': '/dev/mapper/mpathh', '/dev/sdc': '/dev/mapper/mpathh',
'/dev/sdj': '/dev/mapper/mpathg', '/dev/sdk': '/dev/mapper/mpathg'}
Great one line answer by #Selcuk using dictionary comprehension.
An elaborated one along the same line would be:
mpath_dict = {}
for sd, mpath in multipath.items():
mpath_dict[sd] = mpath['mpath']
print(mpath_dict)
Since every value item of "mpath" dictionary is a dictionary itself, you can retrieve values from it as you would do it in a dictionary.
I have created a dictionary with empty values as "dictionary". I also have a list named contig_list_numbers(first list in the output) . What i have been trying to do is to append the values from contig_list_numbers into the
the dictionary values.
what i want is to place all string values after ":" in list as the values in the dictionary.ex- contig1000:254', 'contig1000:170', 'contig1000:1114', 'contig1000:2199' this to be converted into {contig1000 : [254,170,1114,2199]}
can someone help me out ??
first list is contig_list_numbers
last is dictionary with empty values
You can split the string by : to get key and value, store them to dictionary
and append the value if key already exist.
So the solution would be:
dictionary = {}
contig_list_numbers = ['contig1000:254', 'contig1000:170', 'contig1000:1114', 'contig1000:2199']
for astring in contig_list_numbers:
key, value = astring.split(":")
if key not in dictionary:
dictionary[key] = [value]
else:
dictionary[key].append(value)
I have 2 dict, one original and one for mapping the original one's key to another value simultaneously,for instance:
original dict:
built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}},
'Germany':{'ajax-amsterdam-youth':{'lance':'test2'}}}
mapping dict:
club_team_dict={'deportivo-cuenca-u20':'deportivo','ajax-amsterdam-youth':'ajax'}
It works well if I use the following code to change the key of the nested dict of original dict,like
def club2team(built_dict,club_team_dict):
for row in built_dict:
# print test_dict[row]
for sub_row in built_dict[row]:
for key in club_team_dict:
# the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it
if sub_row==key:
built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row)
return built_dict
and the result:
{'Germany': {'ajax': {'lance': 'test2'}}, 'China': {'deportivo': {'danny': 'test1'}}}
so far so good, however if I have a dict with multiple key mapping to the same key,for example,my original dict is like
built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}},
'Germany':{'ajax-amsterdam-youth':{'lance':'test2'},
'ajax-amsterdam':{'tony':'test3'}}}
and the mapping dict with more then 1 key mapping to the same value,like:
club_team_dict={'deportivo-cuenca-u20':'deportivo',
'ajax-amsterdam-youth':'ajax',
'ajax-amsterdam':'ajax'}
as you can see, both 'ajax-amsterdam-youth'and 'ajax-amsterdam-youth' are mapping to 'ajax',and the trouble is when I use the same code to execute it, the original dict's size has been changed during the iteration
RuntimeError: dictionary changed size during iteration
I want to get a result with nested list for the same key like this
{'Germany': {'ajax':[{'lance': 'test2'},
{'tony' : 'test3'}]}},
'China': {'deportivo': [{'danny': 'test1'}]}}
Well I have found a solution for this,the code:
def club2team(built_dict,club_team_dict):
for row in built_dict:
# print test_dict[row]
for sub_row in built_dict[row].keys():
for key in club_team_dict:
# the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it
if sub_row==key:
# built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row)
built_dict[row].setdefault(club_team_dict[sub_row],[]).append(built_dict[row].pop(sub_row))
return built_dict
pay attention to the for sub_row in built_dict[row].keys(): and setdefault() method, I used to believe that in python 2.7, the default iteration for dict is just iterate the keys(), however, this time it proves it's a little different, maybe you have better solution, please show me and it will be appreciate,thank you
Here is my code:
for response in responses["result"]:
ids = {}
key = response['_id'].encode('ascii')
print key
for value in response['docs']:
ids[key].append(value)
Traceback:
File "people.py", line 47, in <module>
ids[key].append(value)
KeyError: 'deanna'
I am trying to add multiple values to a key. Throws an error like above
Check out setdefault:
ids.setdefault(key, []).append(value)
It looks to see if key is in ids, and if not, sets that to be an empty list. Then it returns that list for you to inline call append on.
Docs:
http://docs.python.org/2/library/stdtypes.html#dict.setdefault
If I'm reading this correctly your intention is to map the _id of a response to its docs. In that case you can bring down everything you have above to a dict comprehension:
ids = {response['_id'].encode('ascii'): response['docs']
for response in responses['result']}
This also assumes you meant to have id = {} outside of the outermost loop, but I can't see any other reasonable interpretation.
If the above is not correct,
You can use collections.defaultdict
import collections # at top level
#then in your loop:
ids = collections.defaultdict(list) #instead of ids = {}
A dictionary whose default value will be created by calling the init argument, in this case calling list() will produce an empty list which can then be appended to.
To traverse the dictionary you can iterate over it's items()
for key, val in ids.items():
print(key, val)
The reason you're getting a KeyError is this: In the first iteration of your for loop, you look up the key in an empty dictionary. There is no such key, hence the KeyError.
The code you gave will work, if you first insert an empty list into the dictionary under to appropriate key. Then append the values to the list. Like so:
for response in responses["result"]:
ids = {}
key = response['_id'].encode('ascii')
print key
if key not in ids: ## <-- if we haven't seen key yet
ids[key] = [] ## <-- insert an empty list into the dictionary
for value in response['docs']:
ids[key].append(value)
The previous answers are correct. Both defaultdict and dictionary.setdefault are automatic ways of inserting the empty list.