-1

How can I get the specific value of a specific key in a list of dictionaries?

I'm trying to write a code that will search the list of dictionaries, and see if my input is in the values for the key'c'.

ex. d1={'a':'b','c':'d','e':'f'},d2,d3 and so on.

when i get an input, let's say ,'d', i want the program to check if there is 'd' in the values for key 'c'.

Then I want to print the value for key'c' of the dictionary that had 'd' as the value for key 'c'.

the result should look like this.

choice=input('choose the alphabet')
choose the alphabet: d
a

the possible answer? that was suggested was helpful, but I'm still lost on how to approach the several dictionaries in the list..

dict_A={'name':'A','goods':'clothing','price':200}
dict_B={'name':'B','goods':'interior','price':180}
dict_C={'name':'C','goods':'clothing','price':50}

shops_all=[dict_A,dict_B,dict_C]

choice=input('what kind of stuff are you looking for ')
price=int(input('your budget? '))

for item in shops_all:
    if choice == item['goods']:
        if price <= item['price']:
            print('shop {},price{}dollars'.format(item['shop'],item['price']))
        else:
            print('no such shop')
  • 2
    There's no such thing as "second" key. dictionaries are unordered. – Rocky Li Apr 28 '19 at 04:09
  • And they use `{}`. Your syntax is invalid. Also the are designed for key lookup not for value lookup. – Klaus D. Apr 28 '19 at 04:10
  • yup fixed them... I understand the rules! hope my question is more clear now – pythonnewbie Apr 28 '19 at 04:13
  • I'm making a list of shops, and each shop is assigned as a list with keys like 'location' 'name' 'price' etc. when input is California, i want to see if there are shops that have california as location's value, and then print the values for 'name' 'price' for that specific dictionary. – pythonnewbie Apr 28 '19 at 04:15
  • 1
    Possible duplicate of [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – Cohan Apr 28 '19 at 04:18
  • but i have several dictionaries.... should i use 'for' to search through them? – pythonnewbie Apr 28 '19 at 04:22
  • keep all dictionares on the list `[{'a':'b','c':'d','e':'f'}, {'a':'b','c':'d','e':'f'}, ...]` or in other dictionary `{"d1": {'a':'b','c':'d','e':'f'}, "d2":{'a':'b','c':'d','e':'f'}, ...}` and then you can use `for` loop. – furas Apr 28 '19 at 04:24
  • 1
    Yes, iterate over the list. Or if you really want, you can turn the list of dicts into a pandas dataframe and go from there, but pandas has a bit of a curve to it. – Cohan Apr 28 '19 at 04:24
  • we're still learning about for loops at school, so I'm kind of lost when using them... for place in range(len(shop_all)): if location in place: would this be the right approach? – pythonnewbie Apr 28 '19 at 04:30
  • At the last code block. I must have done something wrong...it works when i put clothing 200, but not when i put clothing 300.. could someone point the error out? – pythonnewbie Apr 28 '19 at 05:35

1 Answers1

2

Given a list of dictionaries that contain information about shops:

shops = [
    {"name": "Barneys New York", "state": "NY"},
    {"name": "Bealls", "state": "CO"},
    {"name": "Belk.", "state": "PA"},
    {"name": "Boscov's.", "state": "AL"},
    {"name": "Dillard's.", "state": "OH"},
    {"name": "Hudson's Bay Company", "state": "NY"},
    {"name": "Lord & Taylor", "state": "CA"},
    {"name": "Saks Fifth Avenue", "state": "NY"},
    {"name": "J. C. Penney.", "state": "MD"},
    {"name": "Kohl's.", "state": "VA"},
]

If you want to iterate of the list, you don't need an iterator counter. Calling the variable you want to iterate over will give you each element one at a time.

for shop in shops:

The following lines would accomplish the same thing, but it's a hell of a lot more difficult to read and introduces a lot of unnecessary operations. The shops would already be iterated through to generate the len(), then you are creating another iterator range(). Finally, you're indexing something that could have just easily been passed to you. So yeah, use the simpler way to loop.

for i in range(len(shops)):
    shop = shops[i]

Now, if you want to find if that shop is in a given state, you can check to see if it's in one of the dictionaries keys by using if <state> in shop.values() or if you know you're looking for the state key/value pair, you can evaluate the dictionary key directly with shop['state']. If that matches the state you want, just print out what you need.

for shop in shops:
    if shop['state'] == 'CA':
        print(shop['name'])

# Lord & Taylor

At this point, you can access any of the portions of the shop's dictionary and do any valid logic.

With your code, you are better off putting everything in a list right off the bat. If you are receiving information in a given way, then you'll have to deal with it, but if you're hard coding it into your file like this, then go ahead and turn this:

dict_A = {'name':'A', 'goods':'clothing', 'price':200}
dict_B = {'name':'B', 'goods':'interior', 'price':180}
dict_C = {'name':'C', 'goods':'clothing', 'price':50}

shops_all = [dict_A, dict_B, dict_C]

into this

shops_all = [
    {'name':'A', 'goods':'clothing', 'price':200},
    {'name':'B', 'goods':'interior', 'price':180},
    {'name':'C', 'goods':'clothing', 'price':50},
]

Now, let's say you want to find clothing and you only have $100.

choice = 'clothing'
price = 100

Now I'm assuming you were intending budget to be the max you wanted to spend, so you have a logic error in your if price <= item['price'] line. Here you are looking where the store price is higher than what you want. So lets flip that to item['price'] <= price. You also had a small error where you put item['shop'] when you meant item['name'] based on your sample data. Once those are fixed, you can give it a shot.

for item in shops_all:
    if choice == item['goods']:
        if item['price'] <= price:
            print('shop {}, price {} dollars'.format(item['name'], item['price']))
        else:
            print('no such shop')
# no such shop
# shop C, price 50 dollars

Now you see the "no such shop" message showing up which is clearly not the case. There are two issues with the code here. 1) the else should be dedented to be with the first if statement and 2) it would still pritnt for shop B. So, this is where a flag variable success could be useful. You can set the variable to false, and flip it to true when you have a match. Then check for it after your done iterating if you want to print a message letting them know they're out of luck. Also, it would be good to check the choice and price at the same time using and.

success = False
for item in shops_all:
    if choice == item['goods'] and item['price'] <= price:
        success = True
        print('shop {}, price {} dollars'.format(item['name'], item['price']))

if not success:
    print('no such shop')

# shop C, price 50 dollars
Cohan
  • 4,384
  • 2
  • 22
  • 40
  • Thanks! Sure helped. After finding the shop that matched my location input, if I want to see if the price is lower, would putting another if statement below if shop['state']=='CA' do? – pythonnewbie Apr 28 '19 at 04:50
  • lower than what – Cohan Apr 28 '19 at 04:51
  • I tried, but it didn't work... for example, if 'Lord & Taylor' 's price is $50, i wrote if price<=shop['price'] – pythonnewbie Apr 28 '19 at 04:53
  • I placed the price as another key and value in the original dict of shops, and would compare the input price with these values @briancohan – pythonnewbie Apr 28 '19 at 04:55
  • Why don't you edit your question post with a little more actual detail of what the data looks like and what your end goal is and where exactly you're having issues. Then once I understand, I can try to help. – Cohan Apr 28 '19 at 04:56
  • I edited my original post..hope this makes it clearer ^^ – pythonnewbie Apr 28 '19 at 05:04
  • Hope that extra bit helps – Cohan Apr 28 '19 at 05:27
  • Oh! Didn't notice that I placed the >= direction wrong (what was I thinking?!) Thanks so much for helping me out! – pythonnewbie Apr 28 '19 at 05:46