Python Forum
Pulling any information from a dictionary with a user input
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pulling any information from a dictionary with a user input
#5
It's just about accessing dictionary data. You may need to loop (one way or another) over the dict to find all elements that satisfy certain criteria. below are some examples, but it's not exhaustive list of approaches.

 assuming dict is named periodic_table (I will come to this a bit later)

# using for loop
for element in periodic_table.values():
    if element['Type'].endswith('Metal'):
        print(element)

# using list comprehension
radioactive_elements = [element['name'] for element in periodic_table.values() if element['Radioactive']]
print(radioactive_elements)

# using built-in function filter
for element in filter((lambda x: x['Type'] == 'Nonmetal'), periodic_table.values()):
    print('{name} : {Mass}'.format(**element))
you create your dict in a very naive, although perfectly valid way.
Instead of creating empty dict and assign key, value pairs, you can simply create dict like this
periodic_table = {'H':{'name': 'Hydrogen', 'number': 1, 'Mass': 1.008, 'Type': 'Nonmetal', 'Radioactive': False},
'He': {'name': 'Helium', 'number': 2, 'Mass': 4.003, 'Type': 'Noble Gas', 'Radioactive': False},
.... here go rest of the elements ....
}


I would make all keys either lower case or first char upper case. at the moment some of the keys are lowercase , e.g. 'name' and some have first char upper case, e.g. 'Mass'. I will choose one or the other and stick to it.
iFunKtion already mentioned database and this is fine, but at least I would consider to put the periodic table data in external file, e.g. json (see attached).

the access it like this

import json
with open('mendeleev.json', 'r') as f:
    periodic_table = json.load(f)
Finally, if you plan to work with periodic table in long run, you don't need to invent the wheel - there are several packaged that have implemented the periodic table of elements and provide nice functionality to work with the table. have a look at some of them:

https://pypi.python.org/pypi?%3Aaction=s...odic+table
Reply


Messages In This Thread
RE: Pulling any information from a dictionary with a user input - by buran - Nov-21-2017, 07:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  User Input to mySQL database newbie1 3 4,260 Aug-26-2020, 10:42 AM
Last Post: newbie1
  Download images generated by user input one_of_us 0 2,534 Mar-26-2019, 07:58 AM
Last Post: one_of_us
  Flask: Cookies for Saving User Input ? jomonetta 2 3,562 Nov-03-2018, 10:47 AM
Last Post: j.crater
  Can not get information from User o0TarZan0o 5 5,085 Feb-16-2017, 06:27 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

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