0

I want to build a segment dictionary like segment tree. I mean I want to use sequence (11, 22) as key, if the input value like 11 it should be use the same key. how to do it.

for example the dictionary is {(11, 22): 35, (44, 45):12}. I want to write fellows:

for i in dictionary:
    blad
    blad

how to change the dictionary function make it can use "in" operator?

OmG
  • 18,337
  • 10
  • 57
  • 90
user504909
  • 9,119
  • 12
  • 60
  • 109

2 Answers2

0

When you use tuples are dictionary keys they have to be used fully to reference that value.

In your case (11,22) is a key. And you may not use them separately to identify values.

Tuples are used as keys when both its elements mean something together. For example : {(<first_name>,<last_name>): <money_owed>}

Why elements of tuples as keys wouldn't be right?

Eg : {('John','Well'):100, ('John','Mann'):200}

Here the first_names are both John and we use a tuple to uniquely identify the key.

What you want is like a list as a key and you may not have a list as a dictionary key.

What you may do is keep them separate(different keys with same value):

{11: 35, 22: 35, 44:12, 45:12}

Refer : Dict keys in python

You may use this method(you will get issues if you have repetition of key elements, and if you do have repetitions you shouldn't use elements in the tuples to identify values):

l=[]
for x in a:
   for i in x:
     l.append({i:a[x]})

With this you get an output like: [{11: 35}, {22: 35}, {44:12}, {45:12}]

Then you may us it as a list of dictionaries.

Ani Menon
  • 27,209
  • 16
  • 105
  • 126
  • That's a tuple not a list. And tuples are hashable. – Pythonista May 30 '16 at 03:37
  • @Pythonista Updated answer. Tuple elements may not be used separately as keys. The OP is trying to have a list as a key which is not allowed. – Ani Menon May 30 '16 at 04:00
  • @AniMenon I know I should use the full tuple as a key. – user504909 May 30 '16 at 07:07
  • @AniMenon I know python should use the full tuple as a key. But my question is how to make a segment dictionary which if a value inside the distance of key pairs will be matched. – user504909 May 30 '16 at 07:13
  • @user504909 good, and you may not use part of keys to refer to the value if your key tuple elements are same. Do check the update to answer if your key tuples have all unique values and none the elements of those tuples are same. – Ani Menon May 30 '16 at 08:35
0

write your won insert method

 def insert(key,value,dict):
     for i in dict:
             if key in i:
                     dict[i]=value
Vikas Madhusudana
  • 1,482
  • 1
  • 10
  • 20