Python Forum
Printing specific values out from a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Printing specific values out from a dictionary
#1
Hi All,

So I have created a dictionary:

myDict = {
  "Name": {"Kindle Fire", "Samsung Galaxy Tab", "Dell Streak", "Apple iPad", "Lenovo Tab"},
  "Memory": {16, 8, 16, 64, 32},
  "Processor": {2.2, 1.2, 1.8, 2.65, 2.3},
  "Cost": {199, 114.99, 59.99, 319, 129},
}
I want to write a bit of python code that will print out the keys and the values of the devices that are over 150 in cost. However I am not sure how to do that? Any idea or a place where to look?

Thanks
Reply
#2
Maybe restructure the dict like this
myDict = {
    'Kendle Fire': {'Memory': 16, 'Processor': 2.2, 'Cost': 199 },
    'Samsung Galaxy': {'Memory': 8, 'Processor': 1.2, 'Cost': 114.99},
    'Dell Streak': {'Memory': 16, 'Processor': 1.8, 'Cost': 59.99},
    'Apple IPad': {'Memory': 64, 'Processor': 2.65, 'Cost': 319},
    'Lenovo Tab': {'Memory': 32, 'Processor': 2.3, 'Cost': 129}
}

for item in myDict.keys():
    for data, info in myDict[item].items():
        if info > 150:
            print(item, myDict[item])
output
Output:
Kendle Fire {'Memory': 16, 'Processor': 2.2, 'Cost': 199} Apple IPad {'Memory': 64, 'Processor': 2.65, 'Cost': 319}
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
Note that values in your dict are set, i.e. unordered collection
Gribouillis likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
(Apr-12-2023, 06:42 PM)menator01 Wrote: Maybe restructure the dict like this
myDict = {
    'Kendle Fire': {'Memory': 16, 'Processor': 2.2, 'Cost': 199 },
    'Samsung Galaxy': {'Memory': 8, 'Processor': 1.2, 'Cost': 114.99},
    'Dell Streak': {'Memory': 16, 'Processor': 1.8, 'Cost': 59.99},
    'Apple IPad': {'Memory': 64, 'Processor': 2.65, 'Cost': 319},
    'Lenovo Tab': {'Memory': 32, 'Processor': 2.3, 'Cost': 129}
}

for item in myDict.keys():
    for data, info in myDict[item].items():
        if info > 150:
            print(item, myDict[item])
output
Output:
Kendle Fire {'Memory': 16, 'Processor': 2.2, 'Cost': 199} Apple IPad {'Memory': 64, 'Processor': 2.65, 'Cost': 319}

This is perfect Thank you, I assumed that nested for Loops would be needed but wasn't sure on the execution. Thanks again.
Reply
#5
Or a dataclass.

https://docs.python.org/3/library/dataclasses.html
from dataclasses import dataclass


@dataclass(order=True)
class Computer:
    name: str
    memory: float
    processor: str
    cost: float


computers = [
    Computer("Kindle Fire", 16, "2.2", 199),
    Computer("Samsung Galaxy", 8, "1.2", 114.99),
    Computer("Dell Streak", 16, "1.8", 59.99),
    Computer("Apple IPad", 64, "2.65", 319),
    Computer("Lenovo Tab", 32, "2.3", 129),
]

print("Computers", *sorted(computers), sep="\n")
print("\nBy price", *sorted(computers, key=lambda x: x.cost), sep="\n")
print("\nBy memory", *sorted(computers, key=lambda x: x.memory), sep="\n")
print("\nLess than $150", *(c for c in computers if c.cost < 150), sep="\n")
Output:
Computers Computer(name='Apple IPad', memory=64, processor='2.65', cost=319) Computer(name='Dell Streak', memory=16, processor='1.8', cost=59.99) Computer(name='Kendle Fire', memory=16, processor='2.2', cost=199) Computer(name='Lenovo Tab', memory=32, processor='2.3', cost=129) Computer(name='Samsung Galaxy', memory=8, processor='1.2', cost=114.99) By price Computer(name='Dell Streak', memory=16, processor='1.8', cost=59.99) Computer(name='Samsung Galaxy', memory=8, processor='1.2', cost=114.99) Computer(name='Lenovo Tab', memory=32, processor='2.3', cost=129) Computer(name='Kendle Fire', memory=16, processor='2.2', cost=199) Computer(name='Apple IPad', memory=64, processor='2.65', cost=319) By memory Computer(name='Samsung Galaxy', memory=8, processor='1.2', cost=114.99) Computer(name='Kendle Fire', memory=16, processor='2.2', cost=199) Computer(name='Dell Streak', memory=16, processor='1.8', cost=59.99) Computer(name='Lenovo Tab', memory=32, processor='2.3', cost=129) Computer(name='Apple IPad', memory=64, processor='2.65', cost=319) Less than $150 Computer(name='Samsung Galaxy', memory=8, processor='1.2', cost=114.99) Computer(name='Dell Streak', memory=16, processor='1.8', cost=59.99) Computer(name='Lenovo Tab', memory=32, processor='2.3', cost=129)
ndc85430 likes this post
Reply
#6
As mention bye buran so is it set,then there is one more surprise.
>>> memory = {16, 8, 16, 64, 32}
>>> memory
{16, 8, 32, 64} 
Oops missing one valueđź‘€
So list/tuple would be more suited for this task,and to show an other way,Pandas do also like this kind of structure.
import pandas as pd

my_dict = {
  "Name": ["Kindle Fire", "Samsung Galaxy Tab", "Dell Streak", "Apple iPad", "Lenovo Tab"],
  "Memory": [16, 8, 16, 64, 32],
  "Processor": [2.2, 1.2, 1.8, 2.65, 2.3],
  "Cost": [199, 114.99, 59.99, 319, 129],
}

df = pd.DataFrame(my_dict)
>>> df
                 Name  Memory  Processor    Cost
0         Kindle Fire      16       2.20  199.00
1  Samsung Galaxy Tab       8       1.20  114.99
2         Dell Streak      16       1.80   59.99
3          Apple iPad      64       2.65  319.00
4          Lenovo Tab      32       2.30  129.00

>>> # Select the devices whose cost is over 150 using query
>>> selected_devices = df.query('Cost > 150')['Name']
>>> selected_devices
0    Kindle Fire
3     Apple iPad
Name: Name, dtype: object
Reply
#7
Pandas plays nice with dataclasses.
from dataclasses import dataclass
import pandas as pd


@dataclass(order=True)
class Computer:
    name: str
    memory: float
    processor: str
    cost: float


computers = [
    Computer("Kendle Fire", 16, "2.2", 199),
    Computer("Samsung Galaxy", 8, "1.2", 114.99),
    Computer("Dell Streak", 16, "1.8", 59.99),
    Computer("Apple IPad", 64, "2.65", 319),
    Computer("Lenovo Tab", 32, "2.3", 129),
]

df = pd.DataFrame(computers)
print("All computers", df, sep="\n")
print("\nCheap computers", df[df["cost"] < 150], sep="\n")  # could also use query like snippsat
Output:
All computers name memory processor cost 0 Kendle Fire 16 2.2 199.00 1 Samsung Galaxy 8 1.2 114.99 2 Dell Streak 16 1.8 59.99 3 Apple IPad 64 2.65 319.00 4 Lenovo Tab 32 2.3 129.00 Cheap computers name memory processor cost 1 Samsung Galaxy 8 1.2 114.99 2 Dell Streak 16 1.8 59.99 4 Lenovo Tab 32 2.3 129.00
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Using Lists as Dictionary Values bfallert 8 347 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  Printing out incidence values for Class Object SquderDragon 3 303 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  need to compare 2 values in a nested dictionary jss 2 875 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Creating a numpy array from specific values of a spreadsheet column JulianZ 0 1,133 Apr-19-2022, 07:36 AM
Last Post: JulianZ
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,761 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
Question How to let the user add 'None' to an specific array in a dictionary? noahverner1995 4 1,800 Dec-26-2021, 10:03 AM
Last Post: noahverner1995
  Sum the values in a pandas pivot table specific columns klllmmm 1 4,652 Nov-19-2021, 04:43 PM
Last Post: klllmmm
  Getting values from a dictionary brunolelli 5 3,605 Mar-31-2021, 11:57 PM
Last Post: snippsat
  Python dictionary with values as list to CSV Sritej26 4 3,029 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  Conceptualizing modulus. How to compare & communicate with values in a Dictionary Kaanyrvhok 7 4,035 Mar-15-2021, 05:43 PM
Last Post: Kaanyrvhok

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020