# K-th non-repeating character in Python using list comprehension and OrderedDict

| |

Examples:

` Input: str = pythonengineering, k = 3 Output: r First non-repeating character is f, second is o and third is r. Input: str = pythonengineering, k = 2 Output: o Input: str = pythonengineering, k = 4 Output: Less than k non-repeating characters in input. `

This problem has an existing solution, please refer to the List Comp Representation and

` # Function for finding the kth non-repeating character `
` # in a line `

` from ` ` collections ` ` import ` ` OrderedDict `

` def ` ` kthRepeating (` ` input ` `, k): `

< code class = "comments"> # OrderedDict returns dictionary data

` # structure with input characters `

` # string as keys in the same order as they are `

` # were inserted and 0 as default `

` dict ` ` = ` ` OrderedDict.fromkeys (` ` input ` `, ` ` 0 ` ` ) `

` # now go to the input line to calculate `

` ` ` # frequency of each character `

< p> ` for ` ` ch ` ` in ` ` input ` `: `

` dict ` ` [ch] ` ` + ` ` = ` ` 1 `

` # now retrieve a list of all keys whose value `

` ` ` # 1 from the order dictionary `

` nonRepeatDict ` ` = ` ` [key ` ` for ` ` (key, value ) ` ` in ` ` `

`  dict . iteritems () if value = = 1 ] `

`   # now returns the (k-1) th character from the list above if len (nonRepeatDict) & lt; k: return ’Less than k non - repeating characters in input . ’   else : return nonRepeatDict [k - 1 ]    # Driver function if __ name__ = = "__ main __" :  input = "pythonengineering" k = 3 print kthRepeating ( input , k) `

` `

Output:

` r `

This article courtesy of Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

## Shop Best laptop for Fortnite

\$ Best laptop for Excel

\$ Best laptop for Solidworks

\$ Best laptop for Roblox

\$ Best computer for crypto mining

\$ Best laptop for Sims 4

\$ Best laptop for Zoom

\$499 Best laptop for Minecraft

\$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

NUMPYNUMPY

How to convert Nonetype to int or string?

NUMPYNUMPY

How to specify multiple return types using type-hints

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

## Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method