How to iterate and store variables in a dictionary? - list

I am new to python and my coding experience so far is with MATLAB.
I am trying to understand more about lists and dictionaries as i am using a library about DOEs that takes an dictionary as a passing argument.
But my trouble so far is that this dictionary assumes the form of ex.
DOE={'Elastic Modulus':[10,20,30], 'Density':[1,2,3], 'Thickness':[2,3,5]}
But i need this dictionary to be user defined, for example:
Have an input to define how many variables are needed (in this example are 3: Elastic Modulus','Density'and 'Thickness)
as the variables are defined, it should be able to store values in the dictionary over a for loop.
Is this possible using dictionaries?
Or is it better to use a list and convert in a dicionary later?
Thank you in advance

One can add keys and the corresponding values to a dict one at a time like so:
my_dict = {}
num_entries = int(input("How many entries "))
for _ in range(num_entries):
key = input("Enter the key: ")
value = input("Enter the value: ")
my_dict[key] = value
Presumably you would have a loop to do the entry of key and value for the number of values you wish to enter. Also if you are in python 2 it needs to be raw_input rather than input function. [Edit: Showing how to do the loop, since I noticed that was part of your question]

Related

How do I output a specific item in a list when inputted a number that corresponds to that item? [Indexing?]

Number,IceCream
1,Chocolate
2,Vanilla
3,Mixed
Say if I
Number = input("Flavor?:")
I know that I need to index [0] because the numbers are on the first column. I also know that I will need to use .split(",") to remove the commas and to create a list.
Some assistance would be greatly appreciated!
It's confusing whether you plan to include integers in the list with the strings or not
Method 1: including integers with strings(flavor), create a list of tuples
icecream=[(1,'choc'),(2,'mix'),(3,'blueberry')]
print(icecream[0][1])
print(icecream[2][1])
Note: tuples are immutable
Method 2: I believe the best way to do this would be to use a dictionary instead of list. As dictionary has (Key, value) pairs, you could assign key(integer) to values(flavor), which then would make it easy accessing items just by keys(integers in your case) ex.
Ice_cream_flavors={1:"chocolate", 2:"vanilla", 3:"mixed"} #dictionary
to access values, you could use methods available in dictionary use get(), items()
Note: items() returns a tuple for each key,value pair.
ex.
Ice_cream_flavors={1:"chocolate", 2:"vanilla", 3:"mixed"}
new=Ice_cream_flavors.items()
for k,v in new:
if input==k:
print(v)

how to creat multiple empty dictionaries from names in a list in python?

I need to create multiple dictionaries from a list. if list is ['dic1','dict2'], i want to creat two different dictionaries such as sample_dic1 and sample_dic2.
if I don't use loops, I'll just type:
sample_dic1=dict();sample_dic2=dict()
my question is how to do it in a loop from a name list.
I tried to put the list in loop while each value of the loop equal to dict().
However, it does not assign the left-hand side to dict().
di_list=['dic1','dict2']
for (a) in di_list:
'sample_{}'.format(a)=dict()
I also Tried this. it doesn't give any error. but doesn't work neigher
temp=dict()
di_list=['dic1','dict2']
for (a) in di_list:
temp[a]='sample_{}'.format(a)
temp[a]=dict()
so I want to creat these two dictrionaries from di_list values. with 'sample_{}'.format(a) I can creat my desired name, But binding it to dict() doesn't work. i.e,. sample_{}'.format(a)=dict()
I think you're mixing two things: variables names and values. Variable names do not have a real effective meaning and if you consistently change their names the program remains the same (in fact, it happens in most languages under the hood anyway).
Here is an option to refer to an arbitrary number of values by name, using a dictionary (name->value):
temp=dict()
di_list=['dic1','dict2']
for (a) in di_list:
temp['sample_{}'.format(a)] = dict()
Now you can verify the values are in fact there:
assert temp['sample_dic1'] == {} # True
assert temp['sample_dict2'] == {} # True

compare two dictionary, one with list of float value per key, the other one a value per key (python)

I have a query sequence that I blasted online using NCBIWWW.qblast. In my xml blast file result I obtained for a query sequence a list of hit (i.e: gi|). Each hit or gi| have multiple hsp. I made a dictionary my_dict1 where I placed gi| as key and I appended the bit score as value. So multiple values for each key.
my_dict1 = {
gi|1002819492|: [437.702, 384.47, 380.86, 380.86, 362.83],
gi|675820360| : [2617.97, 2614.37, 122.112],
gi|953764029| : [414.258, 318.66, 122.112, 86.158],
gi|675820410| : [450.653, 388.08, 386.27] }
Then I looked for max value in each key using:
for key, value in my_dict1.items():
max_value = max(value)
And made a second dictionary my_dict2:
my_dict2 = {
gi|1002819492|: 437.702,
gi|675820360| : 2617.97,
gi|953764029| : 414.258,
gi|675820410| : 450.653 }
I want to compare both dictionary. So I can extract the hsp with the highest score bits. I am also including other parameters like query coverage and identity percentage (Not shown here). The finality is to get the best gi| with the highest bit scores, coverage and identity percentage.
I tried many things to compare both dictionary like this :
First code :
matches[]
if my_dict1.keys() not in my_dict2.keys():
matches[hit_id] = bit_score
else:
matches = matches[hit_id], bit_score
Second code:
if hit_id not in matches.keys():
matches[hit_id]= bit_score
else:
matches = matches[hit_id], bit_score
Third code:
intersection = set(set(my_dict1.items()) & set(my_dict2.items()))
Howerver I always end up with 2 types of errors:
1 ) TypeError: list indices must be integers, not unicode
2 ) ... float not iterable...
Please I need some help and guidance. Thank you very much in advance for your time. Best regards.
It's not clear what you're trying to do. What is hit_id? What is bit_score? It looks like your second dict is always going to have the same keys as your first if you're creating it by pulling the max value for each key of the first dict.
You say you're trying to compare them, but don't really state what you're actually trying to do. Find those with values under a certain max? Find those with the highest max?
Your first code doesn't work because I'm assuming you're trying to use a dict key value as an index to matches, which you define as a list. That's probably where your first error is coming from, though you haven't given the lines where the error is actually occurring.
See in-code comments below:
# First off, this needs to be a dict.
matches{}
# This will never happen if you've created these dicts as you stated.
if my_dict1.keys() not in my_dict2.keys():
matches[hit_id] = bit_score # Not clear what bit_score is?
else:
# Also not sure what you're trying to do here. This will assign a tuple
# to matches with whatever the value of matches[hit_id] is and bit_score.
matches = matches[hit_id], bit_score
Regardless, we really need more information and the full code to figure out your actual goal and what's going wrong.

How to access/retrieve values inside of a list within a dictionary?

I feel like this question should have been asked before but I may be too inexperienced in Python to either (1) locate the answer or (2) understand the answer.
I have a dictionary that contains lists. Each key has three values associated with it inside of a list. Since the values are in a list, I assume that means they are indexed. I know that dictionary keys are unordered and normally values are as well. However, since the values are in a list they should be ordered, correct?
I want to write a for loop that will store the first value within each key to a new list. Or, alternatively, I just want to know how to access values in a dictionary!
I tried the following:
name = dictionary of lists
for key, values in name.iteritems():
xCoord = key[1]
print xCoord
However, I get the error: "IndexError: string index out of range." What would be the way to call/retrieve the first value associated with each key? Thank you!
EDIT: I created the dictionary with the following.
inputCSV = r"G:\REDIRECT\GRP\Test\Workspace\GRPNOV16A.csv"
name = {}
with open((inputCSV),'rb') as offenseFile:
read = csv.DictReader(offenseFile)
for row in read:
if row['Defendant'] not in name:
name[row['Defendant']] = []
name[row['Defendant']].append((row['X - Offense'],row['Y - Offense'],row['GRP Status']))
offenseFile.close
EDIT 2: For anyone in the future who is inexperienced and needs a similar question answered. The dictionary code above was creating a tuple within a list within the dictionary. As a result, to access the tuple I had to do:
for key, values in name.iteritems():
xCoord = key[0][1]
print xCoord
Since the values are in a list, shouldn't this be more like it?
for key, values in name.iteritems():
xCoord = values[1]
print xCoord

casting dictionary in kdb

I want to cast dictionary and log it.
dict:(enlist`code)!(enlist`B10005)
when I do
type value dict / 11h
but the key looks like ,code
when I do
type string value dict / 0h
I am not sure why.
I want to concatenate with strings and log it. So it will be something like:
"The constraint is ",string key dict
But it did not work. The constraint will be like each letter for each line. How I can cast the dictionary so I can concatenate and log it.
Have a look at http://code.kx.com/q/ref/dotq/#qs-plain-text for logging arbitrary kdb+ datatypes.
q)show dict:`key1`key2!`value1`value2
key1| value1
key2| value2
q).Q.s dict
"key1| value1\nkey2| value2\n"
There are several things are going on here.
dict has one key/value pair only but this fact doesn't affect how key and value behave: they return all keys and values. This is why type value dict is 11h which is a list of symbols. For exact same reason key dict is ,`code where comma means enlist: key dict is a list of symbols which (in your particular example) happens to have just one symbol `code.
string applied to a list of symbols converts every element of that list to a string and returns a list of strings
a string in q is a simple list of characters (see http://code.kx.com/wiki/Tutorials/Lists for more on simple and mixed lists)
when you join a simple list of characters "The constraint is " with a list of strings, i.e. a list of lists of characters a result cannot be represented as a simple list anymore and becomes a generic list. This is why q converts "The constraint is " (simple list) to ("T";"h";"e",...) (generic list) before joining and you q starts displaying each character on a separate line.
I hope you understand now what's happening. Depending on your needs you can fix your code like this:
"The constraint is ",first string key dict / displays the first key
"The constraint is ",", "sv string key dict / displays all keys separated by commas
Hope this helps.
if you are looking something for nice logging, something like this should help you(and is generic)
iterate through values, and convert to strings
s:{$[all 10h=type each x;","sv x;0h~t:type x;.z.s each x;10h~t;x;"," sv $[t<0;enlist#;(::)]string x]}/
string manipulation
fs:{((,)string[count x]," keys were passed")," " sv/:("Key:";"and the values for it were:"),'/:flip (string key#;value)#\:s each x}
examples
d:((,)`a)!(,)`a
d2:`a`b!("he";"lo")
d3:`a`b!((10 20);("he";"sss";"ssss"))
results and execution
fs each (d;d2;d3)
you can tailor obviously to your exact needs - this is not tested for complex dict values