How to extract a certain element from a dictionary - dictionary

For example:
d = [{'symbol': 'ETH', 'available': '1'}, {'symbol': 'DOGE', 'available': '4'} , {'symbol': 'USD', 'available': '10'}]
I need to extract the available USD which is 10 in the above dictionary, could you please provide me with a proper code?

You can use next() built-in method:
out = next(dct["available"] for dct in d if dct["symbol"] == "USD")
print(out)
Prints:
10

Well, if your language is python you can do:
print([x for x in d if d['symbol'] == 'USD'][0]['available'])
Do keep in mind that USD must exist in the list for it to work.

Related

how would I delete item's in a dictionary within specific parameters?

for my code I want all numbers from a dictionary under 70 to be deleted, I'm unsure of how to specify this and I need it to also delete the associated name with that number as well, either that or only diplay numbers that are 70 or above.
Below is the code that I have in it's entirety:
name = []
number =[]
name_grade = {}
counter = 0
counter_bool= True
num_loop = True
while counter_bool:
stu = int(input("please enter the number of students: "))
if stu < 2:
print("value is too low, try again")
continue
else:
break
while counter != stu:
name_inp = str(input("Enter your name: "))
while num_loop:
number_inp = int(input("Enter your number: "))
if number_inp < 0 or number_inp > 100:
print("The value is too high or too low, please enter a number between 0 and 100.")
continue
else:
break
name_grade[name_inp] = number_inp
name.append(name_inp)
number.append(number_inp)
counter += 1
print(name_grade)
sorted_numbers = sorted(name_grade.items(), key= lambda x:x[1])
print(sorted_numbers)
if number > 70:
resorted_numbers = number < 70
print(resorted numbers)
how would I go about this?
Also if it's also not too much trouble could someone explain in detail about dictionary keys and how the lambda function I've used works? I got help but I would prefer to know the small details on how it's applied and formatted but don't worry if it's a pain to explain.
You can just iterate over the dictionary and filter for values less than 70:
resorted_numbers = {k:v for k,v in name_grade.items() if v<70}
dict.items method returns a list of key-value tuple pairs of a dictionary, so the lambda function is telling the sorted function to sort by the second element in each tuple.

Guidance on missing() in R

Suppose a function, G, takes two arguments; a and b: G(a = some number, b = some number).
Now two situations (wondering what commands to use in each case?):
1- if a user puts G(b = some number), will the if(missing(a)){do this} recognize the complete absence of a argument? AND more importantly:
2- if a user puts G(a =, b = some number), still will the if(missing(a)){do this} recognize a = but lack of some number in front of it?
Defining the function as below doesn't throw an error in both the cases:
ch <- function(a=NA,b=NA){ if(is.na(a)) return(b) else( return(a+b)) }
> ch(b=2)
[1] 2
> ch(a=,b=2)
[1] 2

iferror equivalent in R

Here is the simplified version:
Suppose I am using 'which' function to find a position, say -
position_num=which(df$word=="ABC")
If the value exists it is fine and it returns an integer, but in case it is unable to match it returns integer(0) in such a case I want to assign a default value to position_num=1.
Thanks for the help in advance
Something like the following if() statement would probably do it.
position_num = if(!length(w <- which(df$word == "ABC"))) 1 else w
Here we are just checking to see if the result from which() has a length, because
length(integer(0))
# [1] 0
And we return 1 if it doesn't have a length, and the which() result (w) otherwise.
Would this work for you?
position_num=ifelse(length(which(df$word=="ABC")) != 0,which(df$word=="ABC"),1)

ERROR: `*` has no method matching *(::Variable)

I wrote the following code:
using JuMP
m = Model()
const A =
[ :a0 ,
:a1 ,
:a2 ]
const T = [1:5]
const U =
[
:a0 => [9 9 9 9 999],
:a1 => [11 11 11 11 11],
:a2 => [1 1 1 1 1]
]
#defVar(m, x[A,T], Bin)
#setObjective(m, Max, sum{sum{x[i,j] * U[i,j], i=A}, j=T} )
print(m)
status = solve(m)
println("Objective value: ", getObjectiveValue(m))
println("x = ", getValue(x))
When I run it I get the following error
ERROR: `*` has no method matching *(::Variable)
in anonymous at /home/username/.julia/v0.3/JuMP/src/macros.jl:71
in include at ./boot.jl:245
in include_from_node1 at loading.jl:128
in process_options at ./client.jl:285
in _start at ./client.jl:354
while loading /programs/julia-0.2.1/models/a003.jl, in expression starting on line 21
What's the correct way of doing this?
As the manual says:
There is one key restriction on the form of the expression in the second case: if there is a product between coefficients and variables, the variables must appear last. That is, Coefficient times Variable is good, but Variable times Coefficient is bad
Let me know if there is another place I could put this that would have helped you out.
This situation isn't desirable but unfortunately we haven't got a good solution yet that retains the fast model construction capabilities of JuMP.
I believe the problem with U is that it is a dictionary of arrays, thus you first need to index into the dictionary to return the correct array, then index into the array. JuMP's variables have more powerful indexing, so allow you to do it in one set of [].
I resolved my problem: constants must preceed variables as I read somewhere, moreover it seems that an array of constants must be used as an array of arrays while variables can be used as matrices.
Here's the correct line:
#setObjective(m, Max, sum{sum{U[i][j]*x[i,j], i=A}, j=T} )

Pythonic shorthand for keys in a dictionary?

Simple question: Is there a shorthand for checking the existence of several keys in a dictionary?
'foo' in dct and 'bar' in dct and 'baz' in dct
all(x in dct for x in ('foo','bar','baz'))
You can use all() with a generator expression:
>>> all(x in dct for x in ('foo', 'bar', 'qux'))
False
>>> all(x in dct for x in ('foo', 'bar', 'baz'))
True
>>>
It saves you a whopping 2 characters (but will save you a lot more if you have a longer list to check).
{"foo","bar","baz"}.issubset(dct.keys())
For python <2.7, you’ll have to replace the set literal with set(["foo","bar","baz"])
If you like operators and don’t mind the performance of creating another set, you can use the <= operator on the set and the dict’s keyset.
Both variations combined would look like:
set(["foo","bar","baz"]) <= set(dct)
Finally, if you use python 3, dict.keys() will return a setlike object, which means that you can call the operator without performance penalty like this:
{"foo","bar","baz"} <= dct.keys()

Resources