Suppose i have a string like 'value=sahi' and i want it like {1:s,2:a,3:h,4:i}
is there any function to do like this.
            Asked
            
        
        
            Active
            
        
            Viewed 2,092 times
        
    -9
            
            
         
    
    
        Mohanth Vanaparthi
        
- 21
- 1
- 
                    3`_, word = my_string.split('='); my_dict = {i: c for i, c in enumerate(word, 1)}`. – erip Jun 21 '16 at 11:32
- 
                    1It's really unfortunate this was closed as a duplicate as the duplicate question is asking about an array, while this is a dictionary - which is completely different. – enderland Dec 06 '20 at 13:54
3 Answers
0
            
            
        There isnt a specific function I know of but you can use dict comprehension:
s = "value=sahi"
d = {k+1: v for k, v in enumerate(s.split("=")[1])}
>>> {1: 's', 2: 'a', 3: 'h', 4: 'i'}
 
    
    
        kezzos
        
- 3,023
- 3
- 20
- 37
- 
                    `enumerate` can take an optional starting index, so you don't need `k+1`. – erip Jun 21 '16 at 11:40
0
            
            
        You can do something like this:
value = "value=sahi"
value = value.replace("value=", "")
my_dict = {}
counter = 1
for c in value:
    my_dict[counter] = c
    counter += 1
for k, v in my_dict.iteritems():
    print k, v
 
    
    
        Teemo
        
- 449
- 6
- 23
-1
            
            
        Step 1: split your given string on '='. This separates the part you don't care about and the part you do care about. In Python, we typically use _ to represent a "don't care".
_, word = given_string.split('=')
Step 2: Create a dictionary mapping the 1-indexed position to its respective 0-base-indexed character in the string. In Python, enumerate creates an iterable of tuples that does exactly this with 0-indexed positions. You can give an optional starting index. In this case, we want to start with one.
my_dict = {i: c for i, c in enumerate(word, 1)}
You can clearly do this in one line, but I think it's better to be explicit, especially when comprehensions are already magic. :)
 
    
    
        erip
        
- 16,374
- 11
- 66
- 121