i am a new programmer trying to learn how to code still. I still don't quite know all of the technical info. I am trying to use a for loop on a list of dictionaries, and then inside of that loop, i want to create another loop that enumerates the dictionary keys. Inside of that loop, I then want to print the keys and values. I want the loop to break once the index reaches all of the points.
Dogs_in_Shelter = [{
"type" : "poodle",
"age" : "2",
"size" : "s",
},
{
"type" : "pug",
"age" : "7",
"size" : "m",
},
{
"type" : "lab",
"age" : "10",
"size" : "m",
}
]
for a in Dogs_in_Shelter:
for index, a in enumerate(Dogs_in_Shelter):
while (index <= 2):
print("{} {}".format(index,a["type"]))
index += 1
break
what prints out is:
0 poodle
1 pug
2 lab
0 poodle
1 pug
2 lab
0 poodle
1 pug
2 lab
I want only the first three lines (with the key and value) , not the repetitions.
Any help for a learner?
edit Yes there is an easier way without the nesting loops however i still need to have them nested. Thanks!
No need of extra for loop and while loop.
enumerate function gives you index and by passing type key you can get its value.
for index, a in enumerate(Dogs_in_Shelter):
print("{} {}".format(index, a["type"]))
Using nesting for loop.
Here I have used counter length = 0. Instead of while we should use if to check the counter.
length = 0
for a in Dogs_in_Shelter:
for index, a in enumerate(Dogs_in_Shelter):
if length <= 2 :
print("{} {}".format(index,a["type"]))
length += 1
You only need one for loop for what you want. while loop is also unnecessary. For example,
for index, dog in enumerate(Dogs_in_Shelter):
print(index, dog['type'])
For Python, we don't use upper letters for variables. FYI, Python Naming Convention
In this case, Dogs_in_Shelter should be dogs_in_shelter, or simply dogs.
Related
I have a list like this:
data.append(
{
"type": type,
"description": description,
"amount": 1,
}
)
Every time there is a new object I want to check if there already is an entry in the list with the same description. If there is, I need to add 1 to the amount.
How can I do this the most efficient? Is the only way going through all the entries?
I suggest making data a dict and using the description as a key.
If you are concerned about the efficiency of using the string as a key, read this: efficiency of long (str) keys in python dictionary.
Example:
data = {}
while loop(): # your code here
existing = data.get(description)
if existing is None:
data[description] = {
"type": type,
"description": description,
"amount": 1,
}
else:
existing["amount"] += 1
In either case you should first benchmark the two solutions (the other one being the iterative approach) before reaching any conclusions about efficiency.
I need to make a function that can check a given word and return another word. For example, if the input is "a1", the function will check for this word in the dictionary and return "a".
I know how to code it if it is just a single input word per category using a simple if-else, but I'm still confused if a category has more than 3 words. And I plan to have a lot of data in this dictionary. So a simple if-else would need a lot of code to be written.
this is the example for the input & output that i want:
Input : a2 Output : a
Input : b3 Output : b
If you really just need to strip a single digit number on the end (per your example):
words=['a1','a2','a3','a4','b1','b2','b3','c1','c2','d1']
realwords= set() # empty set, like a list, but can only have each item once, no duplication
for w in words:
realwords.add(w[:-1])
print(realwords)
{'c', 'a', 'b', 'd'}
If you have a more complex problem than single digits, please append it to your question. There are many ways to solve such problems in Python. In the above example I used the concept of the set, which can be very powerful to ensure that no duplication happens. You can convert the set back to a list easily b=list(a)
If I understand your question correctly, you have a list of words and you want to replace a certain word with another word? In many programming languages I think you would use a switch-case statement for something like this. This can be implemented in Python by using a dict:
switch = {
"a1" : "a",
"a2" : "a",
"a3" : "a",
"a4" : "a",
"b1" : "b",
"b2" : "b",
"b3" : "b",
"c1" : "c",
"c2" : "c",
"c3" : "c",
"d1" : "d",
"d2" : "d"
}
test_word = "d1"
answer = switch[test_word]
print(answer) #d
The bracket notation of [ ] used on a dict looks in the dict for a key matching the value within the brackets. It returns the corresponding value of that key in the dictionary. If it is not found it will raise a KeyError.
If you want to return a different value in the case that the key is not found, then you can use .get instead, like so:
switch.get(test_word, "not found")
I have this code using Python:
a = ["Porsche", "Google", "Facebook", "Mercedes", "Audi", "Twitter"]
if "Porsche" in a:
pass
if "Google" in a:
pass
if "Facebook" in a:
pass
if "Mercedes" in a:
pass
if "Audi" in a:
pass
if "Twitter" in a:
pass
But, with this code, I have no idea how I can decrease the number of needed if statements. Is there a better way using Python to do this?
Thank you very much!
I'm not sure if I'm getting your question right. You want less if-Statements? If that's what you want: It depends on what you're doing in the if-Statements. If you do similar thing, that's no problem. Then you could use something like:
if 'Porsche' in a or 'Google' in a:
pass
If you're doing different things, you need all of those if statements.
If you want less if statements, you could use a for loop running through a list.
Example:
a = ["Porsche", "Google", "Facebook", "Mercedes", "Audi", "Twitter"]
# you can change the values to whatever you want
b = ["Porsche", "Google", "Facebook", "Mercedes", "Audi", "Twitter"]
for i in range(len(a)):
if b[i] in a:
pass
An added benefit is that it isn't hard coded, so you can change it to anything you want, and add more programmatically.
Assuming that the pass statements all represent the same code, the conditions can be combined using or:
if ("Porsche" in a) or ("Google" in a) or ("Facebook" in a) or ("Mercedes" in a) or ("Audi" in a) or ("Twitter" in a):
pass
(The parentheses are all optional, but they make the statement much easier to read.)
Simplifying further using a generator expression:
if any((x in a) for x in ("Porsche", "Google", "Facebook", "Mercedes", "Audi", "Twitter")):
pass
(As before, the parentheses around (x in a) are optional but help readability. The other parentheses are required.)
Assuming you want to check if something is a member of the list you can use in to reduce the number of if statements:
companies_list = ["Porsche", "Google", "Facebook", "Mercedes", "Audi", "Twitter"]
count = 0
if "Apple" in companies_list: # O(n)
count += 1
print(count)
However using in on a list is O(n) i.e. it has to check against every item in the list which is not good if you have a lot of items.
Therefore consider using a set rather than a list, since searching in a set has O(1) look up time:
companies_set = {"Porsche", "Google", "Facebook", "Mercedes", "Audi", "Twitter"}
count = 0
if "Apple" in companies_set: # O(1)
count += 1
print(count)
Output:
0
I know this is probably a pretty basic one, but I've looked and I can't find the answer.
I have a system running trees (nested dict objects) that can be of arbitrary depth.
At present, a subtree index is stored as a list of keys, so in the structure:
example = { 1 : "foo" ,
2 : { 2 : "bar" } ,
3 : { 3 : { 3 : "zip" } } }
the index of "foo" is [1], the index of "bar" is [2,2] and the index of "zip" is [3,3,3].
At the moment, I'm iterating through the list with a for loop :
pointer = root_of_tree
for index in index_list :
pointer = pointer[index]
This works pretty well, but it strikes me that Python is the sort of language that might have a built-in way of handling this case.
Is there a one-line solution? Perhaps a method of the iterable class?
I am learning programming in Python. My task is to create two dictionaries with these values:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15
}
I am tasked to print out things about the dictionary in this format: I was supposed to use a FOR loop to access the data.
apple
price: 2
stock: 0
The instructions said that since the two dictionaries have the same "keys" that I could access both of them at the same time. However I don't know what this means. Learning Python so far has been a breeze, but this has me stumped.
Both dictionaries have a 'banana' key, both have a 'apple' key, etc. Presumably that means you can loop over the keys of one and rely on the same key being present in the other:
for key in stock:
print key, stock[key], prices[key]
The above code will print the keys in stock, adding the value from that dictionary and also looking up the value in prices. If prices does not have the same keys, the code would fail with a KeyError.
I'll leave the actual output up to you, but now your problem is reduced to calculating the stock value.
A dictionary is a list of "key: value" pairs. When you want to get the value from a dictionary you specify the key which points to that value. Since both dictionaries you mentioned have the same keys (e.g., apple, banana), you can use the same key to get values out of both of them.
In order to get all of the keys in a dictionary, you can use the "keys" function. So the code you want is:
for key in prices.keys():
print(key)
print("prices: %s" % prices[key])
print("stock: %s" % stock[key])