Python Forum
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dictionary keys
#1
How do I get multiple keys in a dictionary to point to one item?
I keep getting key errors when I call more than one key.
I want two dics where all the keys in one point to item '1' and all the keys in the other point to item '2'.
I will then convert items '1' and '2' to ints so I can sum them and use the sum as a boolean check(3 = True).
names = {'Taft':'1', 'Wilson':'1', 'Cleveland':'1'}
print names['Taft', 'Wilson']
Error:
Traceback (most recent call last):  File "nav.py", line 3, in <module>    print names['Taft', 'Wilson'] KeyError: ('Taft', 'Wilson')
Reply
#2
Well, all your keys do point to the same item (or that is, items that are all equal to each other). You're just printing them wrong:

for dude in ['Taft', 'Wilson']:
    print names[dude]
A defaultdict from the collections module would be easier for this. However, if you what you want to do is find the keys in both dictionaries, use sets instead:

>>> x = set(range(5))
>>> y = set(range(1, 8))
>>> x.intersection(y)
set([1, 2, 3, 4])
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
direct = raw_input('Enter a street name.\n> ')

names = {'Taft':'1', 'Wilson':'1', 'Cleveland':'1'}
I need the output to look like this.
Output:
Enter a street name. > Taft 1
Reply
#4
names[direct]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding keys and values to a dictionary giladal 3 2,488 Nov-19-2020, 04:58 PM
Last Post: deanhystad
  access dictionary with keys from another and write values to list redminote4dd 6 3,251 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE
  Drop Keys From Dictionary donnertrud 8 3,708 May-30-2020, 11:39 AM
Last Post: DeaD_EyE
  Problem adding keys/values to dictionary where keynames = "property" and "value" jasonashaw 1 2,053 Dec-17-2019, 08:00 PM
Last Post: jasonashaw
  Checking if the combination of two keys is in a dictionary? mrsenorchuck 6 3,896 Dec-04-2019, 10:35 AM
Last Post: mrsenorchuck
  Retrieving dictionary keys within with another dictionay bazcurtis 8 2,842 Oct-29-2019, 10:06 PM
Last Post: bazcurtis
  json.dumps to keep dictionary keys batchenr 1 2,017 May-14-2019, 11:17 AM
Last Post: buran
  Reference new dictionary keys with a variable slouw 4 2,899 May-07-2019, 03:30 AM
Last Post: slouw
  Get specific key from multiple keys in python dictionary pradeepkumarbe 0 2,125 Mar-24-2019, 07:23 PM
Last Post: pradeepkumarbe
  Most efficient way to define sub keys of a dictionary? wrybread 1 2,121 Feb-21-2019, 12:23 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

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