There are two conditions for a droid to develop a personality. The first is a Heuristic Processor, which is an advanced processor that allowed a droid to learn as it worked, as opposed to needing complete programming, this is the piece that allowed a droid to act as an AI as opposed to acting as a computer. http://starwars.wikia.com/wiki/Heuristic_processor
The second piece is called Metaprogramming, and is what allowed a droid to alter its own code in order to better adapt to its environment. So, it is perfectly reasonable that a droid that hung around with murderers and killed people would develop a matching personality. Granted, just like with humans, it was always hard to tell exactly how a droid's metaprogramming would turn out, especially with the decision logic of a heuristic processor. http://starwars.wikia.com/wiki/Metaprogramming
This, in turn, is what led to memory wipes on droids. When coupled together, metaprogramming and heuristic processors could result in a droid that deviated severely from its initial programming design and may even start to behave in a way contrary to its purpose. To that end, they would wipe out a droid's memory and reset it to factory settings, thus clearing out all but their baseline personality. (3PO units, as protocol droids are designed to be subservient, hence C-3PO retaining his personality despite his memory wipe at the end of Ep 3. As for R2, he's never had a memory wipe) http://starwars.wikia.com/wiki/Memory_wipe
TL;DR; Many droids can alter their own programming and learn from experience, this causes them to start acting in ways different from the 'baseline' giving rise to what we would call 'personality'